【问题标题】:In R: How to generate a subset of a data table based on its common elements with two lists of characters在 R 中:如何根据具有两个字符列表的公共元素生成数据表的子集
【发布时间】:2019-06-11 13:37:56
【问题描述】:

我陷入了这个问题,我不确定哪种方法更有效! 我想根据两个字符列表生成一个数据表: 我的第一个 data.table 是:

sample 1   sample 2     N
   a         b          2
   c         c          1
   b         c          3
   c         d          2
   a         c          3
   d         f          1
   d         h          3

如果列表是:

List1= list('a','b')
List2= list('c')

现在,我想查看“sample1”,根据这两个列表找到上述数据表的子集。

我正在寻找的结果是:

    sample 1   sample 2     N
   a         b              2
   c         c              1
   b         c              3
   c         d              2       
   a         c              3

感谢您在这方面的帮助。

【问题讨论】:

  • [] 不是 R 列表.. 你的意思是 List1 = list('a', 'b') 还是 List1 = c('a', 'b')
  • 我的错,List 1 = list('a', 'b')
  • 请格式化您的代码。应该是list('a', 'b')

标签: r filter datatable dplyr subset


【解决方案1】:

我们可以从base R使用subset

subset(df2, sample1 %in% unlist(c(List1, List2)))

数据

df2 <- structure(list(sample1 = c("a", "c", "b", "c", "a", "d", "d"), 
sample2 = c("b", "c", "c", "d", "c", "f", "h"), N = c(2L, 
1L, 3L, 2L, 3L, 1L, 3L)), class = "data.frame", row.names = c(NA, 
-7L))

List1 <- list('a', 'b')
List2 <- list('c')

【讨论】:

    【解决方案2】:

    有什么阻止您合并列表然后按结果过滤吗?

    例如:

    list <- c(unlist(List1), unlist(List2))
    df <- filter(df, `sample 1` %in% list)
    

    【讨论】:

      【解决方案3】:
      DT[`sample 1` %in% unlist(list(List1, List2))]
         sample 1 sample 2 N
      1:        a        b 2
      2:        c        c 1
      3:        b        c 3
      4:        c        d 2
      5:        a        c 3
      

      数据

      List1 = list('a', 'b')
      List2= list('c')
      DT <- fread(
      "sample 1,  sample 2,  N
       a,         b,          2
       c,         c,          1
       b,         c,          3
       c,         d,          2
       a,         c,          3
       d,         f,          1
       d,         h,          3")
      

      【讨论】:

        猜你喜欢
        • 2022-08-02
        • 1970-01-01
        • 2017-04-19
        • 1970-01-01
        • 2012-05-13
        • 2015-10-06
        • 1970-01-01
        • 2012-12-07
        • 2023-01-19
        相关资源
        最近更新 更多