【问题标题】:r data table subset multiple conditions patternsr 数据表子集多个条件模式
【发布时间】:2020-07-16 18:51:57
【问题描述】:

简单来说,我有:

一个数据表:names(DT) <- c("FirstName","BirthDate",otherscolumns)

两个向量:firstname <- c("one","two","three","for") & birthdate <- c("1992-01-01","1993-02-02","1994-03-03","1995-04-04")

第一个 firstname(“one”)对应于第一个 birthdate(“1992-01-01”),以此类推。我想在 DT 只保留与正确名字和正确生日匹配的行。现在我做到了:

data <- DT[FirstName == firstname [1] & BirthDate == birthdate[1] | 
                    FirstName == firstname [2] & BirthDate == birthdate[2] |
                    FirstName == firstname [3] & BirthDate == birthdate[3] | 
                    FirstName == firstname [4] & BirthDate == birthdate[4]]

我确信有一个最好的方法来做到这一点。我尝试生成一个字符串,但它没有用。确实,在我的真实实验中,我有超过 4 个名字,我发现复制过去和更改索引不是一个好方法(主题)

非常感谢您的帮助

【问题讨论】:

    标签: r data.table subset


    【解决方案1】:

    我们可以使用Map 循环遍历'firstname'、'birthdate'、向量,进行比较,然后Reduce| 得到一个逻辑向量,可用于对data.table 进行子集化

    library(data.table)
    data <- DT[DT[, Reduce(`|`, Map(function(x, y) FirstName == x & 
                  BirthDate == y, firstname, birthdate))]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-01
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多