Reputation: 352
I have a large list of dataframes in R that need to be rearranged. I'd like a new list of dataframes where the rows of the nth dataframe are comprised of the nth row of each dataframe in my current list. Here's the setup for a reproducible example:
# 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)
What I want to create, given 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)
I've come up with the following:
# 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)
This gives the desired result, but I'm not sure how I can generalize it so it can be performed on a couple hundred data frames and I'm sure there's a more efficient way to do it. Further, what I gave in my attempt doesn't account for the fact that all my current dataframes are contained in a list (I was thinking of using lapply
somehow for this aspect).
Upvotes: 1
Views: 79
Reputation: 887851
One option would be to convert to array
, use aperm
to transpose the array, reconvert it to a list
of data.frame
s.
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]))
Upvotes: 1