简体   繁体   English

有没有办法自动将彼此下方的 append 数据框列合并为大型数据框列表中的一列?

[英]Is there a way to automatically append data frame columns below each other into one column within large list of data frames?

I have a large list with thousands of data frames included in it.我有一个包含数千个数据框的大列表。 These data frames have multiple columns each.这些数据框各有多个列。 Thereby, I want to automatically bind in each of these data frames the columns into one column.因此,我想在这些数据框中的每一个中自动将列绑定到一列中。 This means that they are appended below each other as shown below.这意味着它们被附加在彼此下方,如下所示。 Thereafter, I would transform the list to a data frame which would have varying column lengths due to the different number of columns within each element in the original list.此后,我会将列表转换为一个数据框,由于原始列表中每个元素的列数不同,该数据框的列长度会有所不同。

From this:由此:

y1 y2
1  4
2  5
3  6

To this:对此:

y1
1
2
3
4
5
6

This should be done for each element in the list, whereby the solution needs to take into account that there are thousands of different data frames, which cannot be mentioned individually (example):这应该针对列表中的每个元素完成,因此解决方案需要考虑到有数千个不同的数据帧,不能单独提及(示例):

df1 = data.frame(
  X1 = c(1, 2, 3),
  X1.2 = c(4, 5, 6)
)
 df2 = data.frame(
  X2 = c(7, 8, 9),
  X2.2 = c(1, 4, 6)
)
df3 = data.frame(
  X3 = c(3, 4, 1),
  X3.2 = c(8, 3, 5),
  X3.3 = c(3, 1, 9)
)
 
listOfDataframe = list(df1, df2, df3)

Final output:最终 output:

df_final = data.frame(
  X1 = c(1, 2, 3, 4, 5, 6),
  X2 = c(7, 8, 9, 1, 4, 6),
  X3 = c(3, 4, 1, 8, 3, 5, 3, 1, 9)
)

Another problem underlying this question is that there will be a differing number of rows, which I do not know how to account for in the data frame, as the columns need to have the same length.这个问题背后的另一个问题是会有不同数量的行,我不知道如何在数据框中考虑,因为列需要具有相同的长度。

Thank you in advance for your help, it is highly appreciated.预先感谢您的帮助,非常感谢。

Structure of list within R: R内部列表结构: 列出带有数据框元素的 L

We can unlist after looping over the list with lapply我们可以在使用unlist遍历listlapply

lst1 <- lapply(listOfDataframe, \(x)
   setNames(data.frame(unlist(x, use.names = FALSE)), names(x)[1]))

-output -输出

lst1
[[1]]
  X1
1  1
2  2
3  3
4  4
5  5
6  6

[[2]]
  X2
1  7
2  8
3  9
4  1
5  4
6  6

[[3]]
  X3
1  3
2  4
3  1
4  8
5  3
6  5
7  3
8  1
9  9

If we need to convert the list to a single data.frame, use cbind.na from qPCR如果我们需要将list转换为单个 data.frame,请使用qPCR中的cbind.na

do.call(qpcR:::cbind.na, lst1)
  X1 X2 X3
1  1  7  3
2  2  8  4
3  3  9  1
4  4  1  8
5  5  4  3
6  6  6  5
7 NA NA  3
8 NA NA  1
9 NA NA  9

Here is a tidyverse solution:这是一个 tidyverse 解决方案:

library(dplyr)
library(purrr)
listOfDataframe %>% 
  map(~.x %>% stack(.)) %>% 
  map(~.x %>% select(-ind))
[[1]]
  values
1      1
2      2
3      3
4      4
5      5
6      6

[[2]]
  values
1      7
2      8
3      9
4      1
5      4
6      6

[[3]]
  values
1      3
2      4
3      1
4      8
5      3
6      5
7      3
8      1
9      9

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

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