如何命名data.frame的未命名的第一列 [英] How to name the unnamed first column of a data.frame

查看:972
本文介绍了如何命名data.frame的未命名的第一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,如下所示:

I have a data frame that looks like this:

> mydf
                   val1     val2
hsa-let-7a         2.139890 -0.03477569
hsa-let-7b         2.102590  0.04108795
hsa-let-7c         2.061705  0.02375882
hsa-let-7d         1.938950 -0.04364545
hsa-let-7e         1.889000 -0.10575235
hsa-let-7f         2.264296  0.08465690

请注意,只有第2和第3列是名称。
我想做的是命名第一列(加上重命名第二和第三)。

Note that from 3 columns only 2nd and 3rd are names. What I want to do is to name the first column (plus rename the 2nd and 3rd).

但是为什么这个命令失败?

But why this command failed?

colnames(mydf) <- c("COL1","VAL1","VAL2");

正确的方法是什么?

它给了我:

Error in `colnames<-`(`*tmp*`, value = c("COL1", "VAL1", "VAL2" :
  'names' attribute [3] must be the same length as the vector [2]


推荐答案

您可以将行名加入数据框,如下所示:

You could join the row names to the dataframe, like this:

mydf <- cbind(rownames(mydf), mydf)
rownames(mydf) <- NULL
colnames(mydf) <- c("COL1","VAL1","VAL2")

或者,一步:

setNames(cbind(rownames(mydf), mydf, row.names = NULL), 
         c("COL1", "VAL1", "VAL2"))
#         COL1     VAL1        VAL2
# 1 hsa-let-7a 2.139890 -0.03477569
# 2 hsa-let-7b 2.102590  0.04108795
# 3 hsa-let-7c 2.061705  0.02375882
# 4 hsa-let-7d 1.938950 -0.04364545
# 5 hsa-let-7e 1.889000 -0.10575235
# 6 hsa-let-7f 2.264296  0.08465690

这篇关于如何命名data.frame的未命名的第一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆