2016-01-06 31 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)'是標準成語。 –

相關問題