2016-01-06 56 views
0

我想根据从另一个数据集中的值,例如在一个数据集重命名列重列...R 3与一个值从另一个数据集

> 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 

现在我想更换X1A,X1B,等......随着答案的内容,所以我尝试使用名称()

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

但结果我得到的是...

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 

我似乎得到ROWNUMBER而不是细胞的实际内容,我也使用得到同样的结果...

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

有什么简单的I'm俯瞰这里?

+0

尝试'名字(问题) - 1] < - as.character(答案$ F1)' –

+1

,你有根本的问题是,当你创建数据帧'answers','F1'被保存为'factor'类。 'factor's被保存为用您传递的值“标记”的数字。因此,当您尝试将值分配为名称时,您只需获取数字即可。你可以通过改变'answers'到'answers = data.frame(F1 = c(“question1”,“question2”,“question3”,“question4”,“question5”),stringsAsFactors = FALSE)'。 – brittenb

回答

0

什么:names(questions) <- c("Area",t(answers))

你需要从要素转换为字符串。

(Strangly我的版本之间:names(questions) <- t(answers$F1)工作)

+2

此代码不起作用。它提供了OP已经获得的相同输出。 – brittenb

+0

谢谢指出。意外地使用旧版本。 – CAFEBABE

+0

如果你坚持使用't()',那么只需't(答案)',因为它会自动转换为字符。但是'as.character(回答$ F1)'是标准成语。 –

相关问题