我在R中有一大堆需要重新排列的数据帧。我想要一个新的数据帧列表,其中 n 数据帧的行由当前列表中每个数据帧的 n 行组成。以下是可重现示例的设置:
# Generate example data
df1 = data.frame(x = c(1.3, 2.7, 3.4, 4.1),
y = c(5.6, 6.3, 7.9, 8.5),
z = c(10, 9, 13, 12))
df2 = data.frame(x = c(1.3, 2.7, 3.4, 4.1),
y = c(5.6, 6.3, 7.9, 8.5),
z = c(13, 13, 8, 14))
# As a list:
current_df_list = list(df1, df2)
我要创建的内容,给定current_df_list
:
# 1st row of df1, df2 become rows of new_df1
new_df1 = data.frame(x = c(1.3, 1.3), y = c(5.6, 5.6), z = c(10, 13))
# 2nd row of df1, df2 become rows of new_df2
new_df2 = data.frame(x = c(2.7, 2.7), y = c(6.3, 6.3), z = c(9, 13))
# 3rd row of df1, df2 become rows of new_df3
new_df3 = data.frame(x = c(3.4, 3.4), y = c(7.9, 7.9), z = c(13, 8))
# 4th row of df1, df2 become rows of new_df4
new_df4 = data.frame(x = c(4.1, 4.1), y = c(8.5, 8.5), z = c(12, 14))
# Final list I want:
new_df_list = list(new_df1, new_df2, new_df3, new_df4)
我想出了以下内容:
# My attempt
new_df_1 = rbind.data.frame(df1[1,], df2[1,])
new_df_2 = rbind.data.frame(df1[2,], df2[2,])
new_df_3 = rbind.data.frame(df1[3,], df2[3,])
new_df_4 = rbind.data.frame(df1[4,], df2[4,])
new_df_list = list(new_df1, new_df2, new_df3, new_df4)
这给出了期望的结果,但我不确定如何将其概括为可以在几百个数据帧上执行它并且我确信这是一种更有效的方法它。此外,我在尝试中给出的内容并未考虑到我所有当前数据帧都包含在列表中的事实(我正在考虑以某种方式使用lapply
来实现此方面)。
答案 0 :(得分:1)
一种选择是转换为array
,使用aperm
转置数组,将其重新转换为list
data.frame
。
ar1 <- array(unlist(current_df_list), c(4,3,2))
ar2 <- aperm(ar1, c(3,2,1))
lapply(seq(dim(ar2)[3]), function(i)
setNames(as.data.frame(ar2[,,i]), letters[24:26]))