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
335 views
in Technique[技术] by (71.8m points)

r - 更改数据框的列名称(Changing column names of a data frame)

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

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

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

In fact this is what am doing:

(事实上,这正在做什么:)

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.

(我没有将它放在循环中,因为我希望每个列名称与您看到的不同。)

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

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

> 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(“"

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

(我同样尝试使用c()函数 - 例如c("premium") ,而不是paste()函数,但无济于事。)

Could someone help me to figure this out?

(有人可以帮我解决这个问题吗?)

  ask by Son translate from so

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

1 Answer

0 votes
by (71.8m points)

Use the colnames() function:

(使用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

You can also subset:

(你也可以分组:)

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

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

...