如何在 r 中堆叠数据框列
通常,您可能希望将两个或多个数据框列堆叠到 R 中的单个列中。
例如,您可能想从这里开始:
person trial outcome1 outcome2 A 1 7 4 A 2 6 4 B 1 6 5 B 2 5 5 C 1 4 3 C 2 4 2
为了那个原因:
person trial outcomes value A 1 outcome1 7 A 2 outcome1 6 B 1 outcome1 6 B 2 outcome1 5 C 1 outcome1 4 C 2 outcome1 4 A 1 outcome2 4 A 2 outcome2 4 B 1 outcome2 5 B 2 outcome2 5 C 1 outcome2 3 C 2 outcome2 2
本教程介绍了您可以在 R 中使用的两种方法来执行此操作。
方法一:使用Base R中的Stack函数
以下代码展示了如何使用 Base R 中的stack函数堆叠列:
#create original data frame data <- data.frame(person=c('A', 'A', 'B', 'B', 'C', 'C'), trial=c(1, 2, 1, 2, 1, 2), outcome1=c(7, 6, 6, 5, 4, 4), outcome2=c(4, 4, 5, 5, 3, 2)) #stack the third and fourth columns cbind (data[1:2], stack (data[3:4])) person trial values ind 1 A 1 7 outcome1 2 A 2 6 outcome1 3 B 1 6 outcome1 4 B 2 5 outcome1 5 C 1 4 outcome1 6 C 2 4 outcome1 7 A 1 4 outcome2 8 A 2 4 outcome2 9 B 1 5 outcome2 10 B 2 5 outcome2 11 C 1 3 outcome2 12 C 2 2 outcome2
方法2:使用Reshape2的Melt函数
以下代码展示了如何使用reshape2库中的Melt函数堆叠列:
#loadlibrary library(reshape2) #create original data frame data <- data.frame(person=c('A', 'A', 'B', 'B', 'C', 'C'), trial=c(1, 2, 1, 2, 1, 2), outcome1=c(7, 6, 6, 5, 4, 4), outcome2=c(4, 4, 5, 5, 3, 2)) #melt columns of data frame melt(data, id. var = c(' person ', ' trial '), variable. name = ' outcomes ') person trial outcomes value 1 A 1 outcome1 7 2 A 2 outcome1 6 3 B 1 outcome1 6 4 B 2 outcome1 5 5 C 1 outcome1 4 6 C 2 outcome1 4 7 A 1 outcome2 4 8 A 2 outcome2 4 9 B 1 outcome2 5 10 B 2 outcome2 5 11 C 1 outcome2 3 12 C 2 outcome2 2
您可以在此处找到合并功能的完整文档。