Subset data.frame by column

前端 未结 3 650
慢半拍i
慢半拍i 2021-01-29 10:26

I have this data.frame:

a <- c(rep(\"1\", 3), rep(\"2\", 3), rep(\"3\",3), rep(\"4\",3), rep(\"5\",3))
b <- c(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)
df <-         


        
相关标签:
3条回答
  • 2021-01-29 10:38

    We can use data.table. We convert the 'data.frame' to 'data.table' (setDT(df)), and set the 'key' as column 'a', then we subset the rows.

    library(data.table)
    setDT(df, key= 'a')[c('2','3')]
    #   a b
    #1: 2 4
    #2: 2 5
    #3: 2 6
    #4: 3 7
    #5: 3 8
    #6: 3 9
    
    0 讨论(0)
  • 2021-01-29 10:40

    what about this?

    library(dplyr)
    df %>% filter(a == 2 | a==3)
      a b
    1 2 4
    2 2 5
    3 2 6
    4 3 7
    5 3 8
    6 3 9
    
    0 讨论(0)
  • 2021-01-29 10:52

    You're confusing == with %in%:

    subset(df, a %in% c(2,3))
    #   a b
    # 4 2 4
    # 5 2 5
    # 6 2 6
    # 7 3 7
    # 8 3 8
    # 9 3 9
    
    0 讨论(0)
提交回复
热议问题