Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
635 views
in Technique[技术] by (71.8m points)

dataframe - In R data.frame, promote rownames to actual column

I have a data frame with one column and row names like this,

 > df
             freq
    hello     4
    sorry     2
    bad       9
    good      4     
    great     1

I want to change that to two columns as below and change row names,

 > df
         word   freq
    1    hello   4
    2    sorry   2
    3    bad     9
    4    good    4
    5    great   1
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
df <- data.frame(freq=c(4,2,9,4,1),row.names=c('hello','sorry','bad','good','great'));
df;
##       freq
## hello    4
## sorry    2
## bad      9
## good     4
## great    1
df <- data.frame(word=rownames(df),freq=df$freq);
df;
##    word freq
## 1 hello    4
## 2 sorry    2
## 3   bad    9
## 4  good    4
## 5 great    1

Edit: On second thought, a better way to do this, which avoids having to hard-code the name of the existing column, and will work with any number of existing columns, is as follows:

df <- data.frame(word=rownames(df),df,row.names=NULL);
df;
##    word freq
## 1 hello    4
## 2 sorry    2
## 3   bad    9
## 4  good    4
## 5 great    1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...