gpt4 book ai didi

r - 在R中使用reduce2()连接数据帧

转载 作者:行者123 更新时间:2023-12-02 12:18:29 24 4
gpt4 key购买 nike

这是a link介绍了reduce2()的使用。

哈德利介绍了这个例子,

you might have a list of data frames that you want to join together, and the variables you use to join will vary from element to element.

我无法想象现在的情况。

我理解了 reduce2() 因为我理解了 a link 中的示例

x <- list(c(0, 1), c(2, 3), c(4, 5))
y <- list(c(6, 7), c(8, 9))
reduce2(x, y, paste)
#> [1] "0 2 6 4 8" "1 3 7 5 9"

但是哈德利描述的例子对我来说很难想象。

谁能描述一下这个例子吗?

最佳答案

一个工作示例

这是哈德利脑海中可能想到的一个例子。想象一下,我们有一个包含这些数据框列表:

library(dplyr)
library(purrr)

df1=data.frame(a = runif(10),b = runif(10),a_0 = c(1,2,2,5,3,1,2,2,5,3))
df2=data.frame(a = runif(5),c = runif(5),b_0 = c(4,1,4,1,4))
df3=data.frame(c = runif(3),d = runif(3),a = runif(3),c_0 = c(5,1,2))
df4=data.frame(b = runif(5),a = runif(5),e = runif(5),d_0 = c(5,1,5,3,1))

lst = list(df1,df2,df3,df4)

现在,我们希望通过两两左连接来减少这些数据帧,这基于公共(public)列;在我们的例子中,这将是列a。相反,我们感兴趣的是根据 by_list 中提供的给定对来左连接数据帧:

by_list=list(c("a_0"="b_0"),c("a_0"="c_0"),c("a_0"="d_0"))

当我们调用reduce2()函数时,我们得到以下输出:

reduce2(lst,by_list,left_join)

The Output of the Function Call

在这里我们可以观察到,这会生成一个列表,其中包含 df1 的列 a_0 中存在的常见元素及其在其他数据帧中的相应对中的所有长格式行。 另请注意,后缀为 a.xa.ya.x.x例如,a.y.y 指示/分隔那些用于任何连接操作的嵌套连接操作中的同名列。

关于r - 在R中使用reduce2()连接数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57744924/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com