[英]Merging a list of data.frames with purrr (reduce/reduce2)
This is my data:这是我的数据:
list_of_data <- list(mtcars[1:26,], mtcars[4:22,], mtcars[3:15,])
I want to merge the all dataframes by their rownames.我想按行名合并所有数据帧。
Merging a lot of data.frames 合并大量data.frames
I know that Reduce
comes pretty handy for a problem like this, but I am not able to get in inside my purrr
workflow.我知道Reduce
对这样的问题非常方便,但我无法进入我的purrr
工作流程。 Can anyone help me?谁能帮我?
I am even not sure if reduce
or reduce2
might be suited to get it work.我什至不确定reduce
或reduce2
是否适合让它工作。 This was my try but it does not work:这是我的尝试,但它不起作用:
list_of_data %>%
map(~select(.x, c(cyl, wt))) %>%
reduce2(~merge(.x, .y, all=TRUE))
If I understand correctly what's your intent:如果我理解正确,你的意图是什么:
library(tibble)
library(purrr)
library(dplyr)
list_of_data %>%
map(~select(.x, cyl, wt)) %>%
map(rownames_to_column) %>%
reduce(full_join, by = "rowname")
We can use dplyr::full_join
with purrr::reduce
to merge multiple dataframes.我们可以使用dplyr::full_join
和purrr::reduce
来合并多个数据帧。 But to be able to merge by rownames, first we need to write them to a column.但是为了能够按行名合并,首先我们需要将它们写入一列。 tibble::rownames_to_column
does that. tibble::rownames_to_column
这样做的。 By default the column is called "rowname".默认情况下,该列称为“rowname”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.