从不等长的列表中加入数据帧 [英] Joining dataframes from lists of unequal length

查看:38
本文介绍了从不等长的列表中加入数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个要合并的数据框列表,我尝试了以下操作:

I have two lists of dataframes that I want to combine, I have tried the following:

A <- data.frame(ID = c(1,2,3),
                var1 = c(3,4,5),
                var2 = c(6,3,2))
B <- data.frame(ID = c(1,2,3),
                var1 = c(4,4,5),
                var2 = c(6,7,3))
C <- data.frame(ID = c(1,2,3),
                var1 = c(1,4,8),
                var2 = c(9,2,3))

list1 <- list(A = A, B = B, C = C)
list2 <- list(A = A, B = B)

combined <- map2(list1, list2, full_join, by = 'ID')

这会返回两个列表长度不同的错误.我想到的唯一另一种方法是向第二个列表添加一个空白数据框,使它们的长度相同.

This returns an error that the two lists are of different lengths. The only other way I have thought of is to add a blank dataframe to the second list so they are the same length.

是否可以合并这两个列表,以便我得到一个列表,其中 A1 与 A2、B1 与 B2、C1 保持原样?

Is it possible combine the two lists so that I get a single list where A1 has been joined with A2, B1 with B2, and C1 remains as it is?

突出显示我还没有命名列表的元素,我现在已经命名了

Its been highlighted that I havent named the elements of the list, I have named them now

推荐答案

如果我们有命名列表,那么我们可以:

If we have named lists, then we could:

list1 <- list(A = A, B = B, C = C)
list2 <- list(A = A, B = B)

x12 <- intersect(names(list1), names(list2))
x1 <- setdiff(names(list1), names(list2))
x2 <- setdiff(names(list2), names(list1))

combined <- c(
  map2(list1[ x12 ], list2[ x12 ], full_join, by = 'ID'),
  list1[ x1 ],
  list2[ x2 ])

这篇关于从不等长的列表中加入数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆