【问题标题】:Select rows based in rows of another data.frame根据另一个data.frame的行选择行
【发布时间】:2019-05-03 21:51:44
【问题描述】:

我有以下这些数据帧:

dt1

Id  Mother Weight  
1    elly     10
2    bina     20
3    sirce    30
4    tina     30
5    lina     40

dt2

Id   Mother  Weight  sex  
1    elly     10      M
2    bina     20      F
3    sirce    30      F

我想从基于 DT2 (ID) 的 DT1 (ID) 中选择行,这样:

新的.dt

Id   Mother  Weight  sex
4    tina     30     NA
5    lina     40     NA

【问题讨论】:

  • @akrun 一个答案是anti_join(a1,a2) - 它不完全相同,但它非常接近并且OP没有表示任何努力搜索许多类似的答案所以在发布之前。关于这个主题有很多关于 SO 的内容。
  • @akrun,同意!它似乎确实是关于 SO 的特定于代码的文化点。例如,与在 r 线程中相比,我看到在 python 线程中标记为欺骗的符合欺骗条件的问题要多得多。不知道为什么会这样。无论如何,我确实认为这个问题与网站上的几个问题非常相似。
  • @andrew_reece 抱歉,之前的问题非常混乱。

标签: r dataframe


【解决方案1】:

这是anti_join的一个选项

library(dplyr)
anti_join(dt1 %>% 
           mutate(sex = NA), dt2, by = 'Id')
#   Id Mother Weight sex
#1  4   tina     30  NA
#2  5   lina     40  NA

数据

dt1 <- structure(list(Id = 1:5, Mother = c("elly", "bina", "sirce", 
"tina", "lina"), Weight = c(10L, 20L, 30L, 30L, 40L)), 
   class = "data.frame", row.names = c(NA, 
-5L))


dt2 <- structure(list(Id = 1:3, Mother = c("elly", "bina", "sirce"), 
    Weight = c(10L, 20L, 30L), sex = c("M", "F", "F")), 
  class = "data.frame", row.names = c(NA, 
-3L))

【讨论】:

    【解决方案2】:
    transform(dt1[!dt1$Id %in% dt2$Id,], sex = NA)
    #  Id Mother Weight sex
    #4  4   tina     30  NA
    #5  5   lina     40  NA
    

    d = merge(dt1, dt2, all = TRUE)
    d[is.na(d$sex),]
    #  Id Mother Weight  sex
    #4  4   tina     30 <NA>
    #5  5   lina     40 <NA>
    

    【讨论】:

    • 您能否对您的代码的作用添加一些解释?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-22
    • 2016-09-09
    • 1970-01-01
    • 2021-03-27
    • 2020-09-25
    • 2021-10-13
    相关资源
    最近更新 更多