在R data.frame中,将行名提升为实际列 [英] In R data.frame, promote rownames to actual column
本文介绍了在R data.frame中,将行名提升为实际列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有这样的列和行名称的数据框,
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
推荐答案
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
编辑:再三考虑,一种更好的方法是避免对现有列的名称进行硬编码,并且可以与任意数量的现有列一起使用,如下所示:
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
这篇关于在R data.frame中,将行名提升为实际列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文