简体   繁体   English

如何将名称附加到R中输出数据框的“列名”?

[英]how to append names to “ column names” of the output data frame in R?

i know that i can change the names of columns using 我知道我可以使用更改列的名称

colnames(x)<-c("Column1" , "Column 2" ,"Column 3", "Column 4")

If I have 如果我有

A<-"Apple"  
B<-"Banana"  

What should I do so that the names of the output data frame will have names like this 我应该怎么做才能使输出数据框的名称具有这样的名称

"Column 1 Apple" "Column 2 Banana" "Column 3 Apple" "Column 4 Banana"

I have looked at Replace "names" of columns of a data frame with different (new) names in another file in R 我查看了R中另一个文件中不同(新)名称的数据框列的替换“名称”
and
How to dynamically assign names to dataframes? 如何动态地为数据帧分配名称?
But I didn't quite understand how to apply it to my case. 但我不太明白如何将它应用到我的案例中。

Just use paste and rely on the fact that R recycles vectors. 只需使用paste并依赖R回收矢量的事实。 As @Richard noted, you should avoid spaces in column/variable names to make your life easier. 正如@Richard所说,你应该避免列/变量名中的空格,以使你的生活更轻松。 make.names can take care of that: make.names可以解决这个问题:

make.names(paste(names(x), c(A,B)))
#[1] "Column1.Apple"  "Column2.Banana" "Column3.Apple"  "Column4.Banana"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM