简体   繁体   English

R使用其他数据集中的值重命名列

[英]R rename column with a value from another dataset

I want to rename columns in one dataset based on the values from another dataset, for example... 我想根据另一个数据集中的值重命名一个数据集中的列,例如...

> set.seed(1234)
> questions = data.frame(Area=c("Zone1","Zone2","Zone3"),
                       X1a=sample(10,3), X1b=sample(10,3), X1c=sample(10,3),
                       X1d=sample(10,3), X1e=sample(10,3))
>questions
   Area X1a X1b X1c X1d X1e
1 Zone1   2   7   1   6   3
2 Zone2   6   8   3   7   9
3 Zone3   5   6   6   5  10

answers = data.frame(F1=c("question1","question2","question3","question4","question5"))
 > answers
         F1
1 question1
2 question2
3 question3
4 question4
5 question5

Now I want to replace X1a,X1b,etc... with the contents in answers, So I tried using names() 现在我想用答案中的内容替换X1a,X1b等...,所以我尝试使用names()

> names(questions)[2:6]<-c(answers[1,],answers[2,],answers[3,],answers[4,],answers[5,])

But the result I get is... 但是我得到的结果是...

   Area 1 2 3 4  5
1 Zone1 2 7 1 6  3
2 Zone2 6 8 3 7  9
3 Zone3 5 6 6 5 10

I seem to get a rownumber instead of the actual contents of the cells, I also get the same result from using... 我似乎得到的是行号而不是单元格的实际内容,使用...我也得到相同的结果。

names(questions)[2:6]<-c(answers[1,1],answers[2,1],answers[3,1],answers[4,1],answers[5,1]) 

Is there something simple I´m overlooking here? 我在这里有一些简单的事情吗?

What about: names(questions) <- c("Area",t(answers)) 关于什么: names(questions) <- c("Area",t(answers))

You need to convert from factor to string. 您需要将因数转换为字符串。

(Strangly my in between version: names(questions) <- t(answers$F1) worked) (很抱歉,我在两个版本之间使用: names(questions) <- t(answers$F1)有效)

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

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