更改R中数据帧的列名称 [英] Changing column names of a data frame in R

查看:542
本文介绍了更改R中数据帧的列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为newprice的数据框(见下文),我想在R中更改我的程序中的列名。

I have a data frame called "newprice" (see below) and I want to change the column names in my program in R.

> newprice
   Chang.  Chang.   Chang.
1     100       36      136
2     120      -33       87
3     150       14      164

其实这就是我所做的:

names(newprice)[1]<-paste("premium")
names(newprice)[2]<-paste("change")
names(newprice)[3]<-paste("newprice") 

我没有把它放在一个循环中,因为我希望每个列的名称都不一样。

I have not put this in a loop because I want each column name to be different as you see.

当我将程序粘贴到R控制台时,这是它给我的输出:

When I paste my program into R console this is the output it gives me:

> names(newprice)[1]<-paste("premium")
Error: unexpected input in "names(newprice)[1]<-paste(""
> names(newprice)[2]<-paste("change")
Error: unexpected input in "names(newprice)[2]<-paste(""
> names(newprice)[3]<-paste("newpremium")
Error: unexpected input in "names(newprice)[3]<-paste(""

我同样尝试使用 c()函数,例如 c(premium),而不是 paste()函数,但无效。

I have equally tried using the c() function-for example c("premium"), instead of the paste() function, but to no avail.

可能有人帮助我解决这个问题?

Could someone help me to figure this out?

推荐答案

使用 colnames()功能:

R> X <- data.frame(bad=1:3, worse=rnorm(3))
R> X
  bad     worse
1   1 -2.440467
2   2  1.320113
3   3 -0.306639
R> colnames(X) <- c("good", "better")
R> X
  good    better
1    1 -2.440467
2    2  1.320113
3    3 -0.306639

您还可以将子集:

R> colnames(X)[2] <- "superduper"

这篇关于更改R中数据帧的列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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