【问题标题】:How to merge datasets by common values for variable如何通过变量的常用值合并数据集
【发布时间】:2018-08-16 06:41:45
【问题描述】:

我想合并 6 个具有 ID 变量的数据集。我想要一个数据集,其 ID 值对所有数据集都是通用的。

我知道这很容易解决,但我还没有遇到帮助主题

例如

id month sbp dpb
D1  3     40  40 
D1  4     10  10
D1  3     20  20
D2  4     30  20
D3  5     10  40
D1  3     40  40

id month sbp dpb
D1  3     40  40 
D1  4     10  10
D2  3     20  20
D4  4     30  20
D3  5     10  40
D1  3     40  40

最终

id month sbp dpb
D1  3     40  40 
D1  4     10  10
D1  3     20  20
D2  4     30  20
D3  5     10  40
D1  3     40  40
D1  3     40  40 
D1  4     10  10
D2  3     20  20
D3  5     10  40
D1  3     40  40

最终数据集中省略了 D4

【问题讨论】:

  • 看来你只想rbind(data1, data2, ...)
  • 我不只是想绑定行。我想合并它们并消除所有 6 个数据集不通用的 ID 行

标签: r merge dataset subset merging-data


【解决方案1】:

由于我们有 6 个数据集(假设对象是 'df1'、'df2'、... 'df6'),在 listmget 中获取它们的值,然后将它们绑定在一起( bind_rows) 和 filter 中的所有 id 并不常见

library(dplyr)
n <- 2 #Based on the example only two objects, change it to 6
mget(paste0("df", seq_len(n))) %>%
          bind_rows(., .id = 'grp') %>% 
          group_by(id) %>% 
          filter(n_distinct(grp)==n) %>%
          ungroup %>%
          select(-grp)
# A tibble: 11 x 4
#   id    month   sbp   dpb
#   <chr> <int> <int> <int>
# 1 D1        3    40    40
# 2 D1        4    10    10
# 3 D1        3    20    20
# 4 D2        4    30    20
# 5 D3        5    10    40
# 6 D1        3    40    40
# 7 D1        3    40    40
# 8 D1        4    10    10
# 9 D2        3    20    20
#10 D3        5    10    40
#11 D1        3    40    40

base R 选项是使用intersect 获取所有数据集中常见的“id”

lst <- setNames(mget(paste0("df", seq_len(n))), NULL)
ids <- Reduce(intersect, lapply(lst, `[[`, 'id'))    
res <- do.call(rbind, lapply(lst, subset, subset = id %in% ids))
row.names(res) <- NULL
res
#   id month sbp dpb
#1  D1     3  40  40
#2  D1     4  10  10
#3  D1     3  20  20
#4  D2     4  30  20
#5  D3     5  10  40
#6  D1     3  40  40
#7  D1     3  40  40
#8  D1     4  10  10
#9  D2     3  20  20
#10 D3     5  10  40
#11 D1     3  40  40

【讨论】:

    【解决方案2】:

    这就是你要找的吗?见以下代码:

    df3 <- subset(df2, df2$id %in% df1$id)      
    df <- rbind(df2, df3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-17
      • 2018-05-11
      • 1970-01-01
      相关资源
      最近更新 更多