2015-01-27 50 views
1

我不能爲了我的生活理解rbind函數。我嘗試過使用這裏的例子,但我無法弄清楚我做錯了什麼。我想要做的就是在第一個數據框下面添加數據。初學rbind函數

是否需要列是相同的名稱或...?

ParticipantA=c("A","B","C","D") 
Score1A=c("21","20","21","21") 
Score2A=c("32","40","32","31") 
Score3A=c("47","50","43","46") 
BlockA=data.frame(ParticipantA,Score1A,Score2A,Score3A) 
BlockA$Major=c("Computer_Science","Computer_Science","Computer_Science","Computer_Science") 
BlockA$Gender=c("Female","Female","Male","Male") 
ParticipantB=c("E","F","G","H") 
Score1B=c("28","28","21","22") 
Score2B=c("30","36","37","32") 
Score3B=c("41","49","49","46") 
BlockB=data.frame(ParticipantB,Score1B,Score2B,Score3B) 
BlockB$Major=c("Medical","Medical","Medical","Medical") 
BlockB$Gender=c("Female","Female","Male","Male") 

回答

1

rbind要求所有列的名稱和類都是相同的。

0

問題在於列標題。 rbind使用列標題來定位它將如何綁定行。列的順序可以不同,R將只使用第一個元素來確定列順序。

或者,在數據框中添加另一列,其中值爲「A」或「B」可以保留您的信息,而不會在列名稱中加入「A」和「B」< - 原因你不能使用rbind。額外的列也可以讓你在R中做更多的分析,例如迴歸和其他線性模型。

這裏是處理你的數據的一種方法:

建立了一套統一的,可用於數據幀「BLOCKa中」和「BlockB」列名的

final_colnames <- c("Block", "Participant", "Score1", "Score2", "Score3") 

創建一個新的列表以確定參與者屬於哪個區塊。

BlockA = c("A", "A", "A", "A") 

以前的數據

ParticipantA = c("A", "B", "C", "D") 
Score1A = c("21", "20", "21", "21") 
Score2A = c("32", "40", "32", "31") 
Score3A = c("47", "50", "43", "46") 

標籤「BLOCKa中」在這裏回收來命名新的數據幀,但不加入「A」的「BLOCKa中」列清單「A」,「前A「」A「。

BlockA = data.frame(BlockA, ParticipantA, Score1A, Score2A, Score3A) 

此時需要添加新列名,以便名稱數和列數相等。

colnames(BlockA) <- final_colnames 

現在你可以添加其餘的列

BlockA$Major = c("Computer_Science", "Computer_Science", "Computer_Science", "Computer_Science") 
BlockA$Gender = c("Female", "Female", "Male", "Male") 

BlockB是相同的過程

BlockB = c("B", "B", "B", "B")    # the extra column 
ParticipantB = c("E", "F", "G", "H") 
Score1B = c("28", "28", "21", "22") 
Score2B = c("30", "36", "37", "32") 
Score3B = c("41", "49", "49", "46") 
BlockB = data.frame(BlockB, ParticipantB, Score1B, Score2B, Score3B) 
colnames(BlockB) <- final_colnames   # renaming the columns 
BlockB$Major = c("Medical", "Medical", "Medical", "Medical") 
BlockB$Gender = c("Female", "Female", "Male", "Male") 

統一列名意味着rbind將現在的工作。

rbind(BlockA,BlockB)