初学者rbind功能

时间:2015-01-27 00:43:15

标签: rbind

我不能为我的生活理解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")

2 个答案:

答案 0 :(得分:1)

rbind要求所有列具有相同的名称和类。

答案 1 :(得分: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")

标签&#34; BlockA&#34;在此处回收以命名新数据框,但不是在添加&#34; BlockA&#34; &#34; A&#34;的列表&#34; A&#34; &#34; A&#34; &#34; A&#34;

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)