合并不同大小的数据框 [英] Merge dataframes of different sizes

查看:61
本文介绍了合并不同大小的数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数据框 d1 d2 分别为:

I have two data frames d1 and d2 respectively as:

x   y  z
10  10 7
10  12 6
11  10 8
11  12 2
12  10 1
12  12 5

x  y  z
10 10 100
11 10 200
12 12 400

我想要这样的东西:

x   y  z
10  10 100
10  12 6
11  10 200
11  12 2
12  10 1
12  12 400

对于这个琐碎的问题,我真的感到很抱歉,我找不到答案。

I am really sorry for the trivial question, I could not get the answer.

推荐答案

根据您的描述,我知道您想替换 z d1 中的值与 d2 z 中的值 x & y 匹配。

From your description I understand that you want to replace the z values in d1 with the z values in d2 when x & y match.

使用基数R:

d3 <- merge(d1, d2, by = c("x","y"), all.x = TRUE)
d3[is.na(d3$z.y),"z.y"] <- d3[is.na(d3$z.y),"z.x"]
d3 <- d3[,-3]
names(d3)[3] <- "z"

给出:

> d3
   x  y   z
1 10 10 100
2 10 12   6
3 11 10 200
4 11 12   2
5 12 10   1
6 12 12 400






使用数据。表 -package:


Using the data.table-package:

library(data.table)

setDT(d1) # convert the data.frame to a data.table
setDT(d2) # idem

# join the two data.table's and replace the values
d1[d2, on = .(x, y), z := i.z]

或一次性:

setDT(d1)[setDT(d2), on = .(x, y), z := i.z]

它给出:

> d1
    x  y   z
1: 10 10 100
2: 10 12   6
3: 11 10 200
4: 11 12   2
5: 12 10   1
6: 12 12 400






使用 dplyr 包:

d3 <- left_join(d1, d2, by = c("x","y")) %>%
  mutate(z.y = ifelse(is.na(z.y), z.x, z.y)) %>%
  select(-z.x) %>%
  rename(z = z.y)

由于版本0.5.0 也可以使用 coalesce -功能(为此向Laurent Hostert致谢,请将其带到我的计算机上注意):

Since release 0.5.0 you can also use the coalesce-function for this (thx to Laurent Hostert for bringing it to my attention):

d3 <- left_join(d1, d2, by = c("x","y")) %>% 
  mutate(z = coalesce(z.y, z.x)) %>% 
  select(-c(z.x, z.y))

这篇关于合并不同大小的数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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