简体   繁体   English

在R中重新排列列表和数据框

[英]Rearranging lists and dataframes in R

I have a list with a large number of data.frames (d=100) each containing a number of variables (v=10). 我有一个包含大量data.frames(d = 100)的列表,每个都包含许多变量(v = 10)。 I would like to rearrange the data so that I instead have a new list of 10 data.frames with 100 columns each, extracting the relevant column from each of the 100 original data.frames. 我想重新排列数据,以便我有一个包含10个data.frames(每个100列)的新列表,并从100个原始data.frames中的每个提取相关列。 So new data.frame1 will have 100 columns each being the 1st column from original data.frames, new data.frame2 will have 100 columns each being the 2nd column from original data.frames,....,n . 因此,新的data.frame1将有100列,分别是原始data.frames的第一列,新的data.frame2将有100列,分别是原始data.frames,....,n的第二列。 What's the best way to rearrange this. 重新安排此的最佳方法是什么。 Thank you in advance. 先感谢您。

Here is a way, using dummy data, as you didn't provide input. 这是一种使用虚拟数据的方法,因为您没有提供输入。

df1 <- df2 <- df3 <- df4 <- df5 <- data.frame(v1 = 1:3, v2 = 4:6)
lst <- mget(ls(pattern = "^df"))

I assume your list looks something like lst above. 我认为您的清单看起来像上面的lst Here we have 5 data frames with 2 columns each and we rearrange it such that we end up with a list of 2 data frame containing 5 columns each. 在这里,我们有5个数据帧,每个数据帧有2列,我们对其进行了重新排列,以便最终得到2个数据帧的列表,每个数据帧包含5列。

split_idx <- seq_len(unique(lengths(lst))) # in your case, this should give you 1:10
out <- split.default(x = Reduce(cbind, lst), split_idx)
#$`1`
#  v1 v1.1 v1.2 v1.3 v1.4
#1  1    1    1    1    1
#2  2    2    2    2    2
#3  3    3    3    3    3

#$`2`
#  v2 v2.1 v2.2 v2.3 v2.4
#1  4    4    4    4    4
#2  5    5    5    5    5
#3  6    6    6    6    6

split.default splits a list along columns. split.default沿列分割列表。


If we need to change the names of each data frame we might do 如果我们需要更改每个数据框的名称,我们可以这样做

out <- lapply(out, function(x) {
  names(x) <- paste0(gsub("(v[0-9]+)\\.+", "\\1", names(x)), "_", 1:5)
  x
  })

out
#$`1`
#  v1_1 v1_2 v1_3 v1_4 v1_5
#1    1    1    1    1    1
#2    2    2    2    2    2
#3    3    3    3    3    3

#$`2`
#  v2_1 v2_2 v2_3 v2_4 v2_5
#1    4    4    4    4    4
#2    5    5    5    5    5
#3    6    6    6    6    6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM