1

I want to be able to access b0.e7, c0.14,...,f8.d4. But right now these are not in a column, but are the "row names". How can I have the row names be 1,2,3,4,5,6,7 and b0.e7, c0.14,...,f8.d4 to be it's own column. Thanks for the help in advance.

df=as.data.frame(c)
df = subset(df, c>7)
df
        c
b0.e7  11
c0.14   8
f8.d1  10
f8.d2   9
f8.d3  11
f8.d4  12

3 Answers 3

3

Try this. The first line assigns a new column that is just the current row names of the data frame. The second line resets the row names to NULL, resulting in a sequence.

> df$new <- rownames(df)
> rownames(df) <- NULL

Which should result in

> df
#    c   new
# 1 11 b0.e7
# 2  8 c0.14
# 3 10 f8.d1
# 4  9 f8.d2
# 5 11 f8.d3
# 6 12 f8.d4

And you can reverse the column order if needed with df[, c(2, 1)]

Sign up to request clarification or add additional context in comments.

4 Comments

I liked your answer before the "another option". You'll have to add a row.names = NULL in there if you want to extend it to an answer that works with a data.frame with many columns (unless you want to add each column manually) at which point... :-)
Right you are, rolled it back
For the curious, Richard's answer here is actually faster than the cbind approach.
When trying this using mutate in a pipe chain, df %>% mutate(name = rownames(df)) fails (no name column is added), but calling x <- rownames(df) then mutate(name = x) has the expected result. Any idea why mutate can't seem to perform rownames?
1

You can make use of the fact that cbind.data.frame can make use of arguments from data.frame, one of which is row.names. That argument can be set to NULL, meaning that a slightly more direct approach than proposed by Richard is:

cbind(rn = rownames(mydf), mydf, row.names = NULL)
#      rn  c
# 1 b0.e7 11
# 2 c0.14  8
# 3 f8.d1 10
# 4 f8.d2  9
# 5 f8.d3 11
# 6 f8.d4 12

Comments

-1

You can try this as well.

rows = row.names(df)
df1 = cbind(rows,df)

1 Comment

Please consider adding a bit of explanation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.