【问题标题】:How to delete rows in a data.frame by a specific condition?如何按特定条件删除 data.frame 中的行?
【发布时间】:2020-11-18 22:30:44
【问题描述】:

我尝试删除 data.frame 中的一些行,但无法解决问题。有人可以帮忙吗?

这是data.frame

   subj trial fix type
1     a     1   1    K
2     a     1   2    T
3     a     1   3    T
4     a     2   1    K
5     a     2   2    K
6     a     2   3    T
7     b     1   1    T
8     b     1   2    K
9     b     1   3    K
10    b     2   1    K
11    b     2   2    T
12    b     2   3    T

并且我希望对于每个主题,在每个试验中 T 第一次出现的行。结果应如下所示:

   subj trial fix type
2     a     1   2    T
6     a     2   3    T
7     b     1   1    T
11    b     2   2    T

【问题讨论】:

    标签: r for-loop if-statement apply


    【解决方案1】:

    使用来自dplyrslice 的一个想法,

    library(dplyr)
    
    df %>% 
     group_by(subj, trial) %>% 
     slice(which(type == 'T')[1])
    
    # A tibble: 4 x 4
    # Groups:   subj, trial [4]
    #  subj  trial   fix type 
    #  <fct> <int> <int> <fct>
    #1 a         1     2 T    
    #2 a         2     3 T    
    #3 b         1     1 T    
    #4 b         2     2 T
    

    【讨论】:

    • 很好的答案!作为补充,slice(which.max(type == 'T')) 也可以。
    【解决方案2】:

    您可以使用filter() + distinct()

    library(dplyr)
    
    df %>%
      filter(type == "T") %>%
      distinct(subj, trial, .keep_all = T)
    
    #    subj trial fix type
    # 2     a     1   2    T
    # 6     a     2   3    T
    # 7     b     1   1    T
    # 11    b     2   2    T
    

    数据

    df <- structure(list(subj = c("a", "a", "a", "a", "a", "a", "b", "b", 
    "b", "b", "b", "b"), trial = c(1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 
    1L, 2L, 2L, 2L), fix = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 
    1L, 2L, 3L), type = c("K", "T", "T", "K", "K", "T", "T", "K", 
    "K", "K", "T", "T")), class = "data.frame", row.names = c("1", 
    "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))
    

    【讨论】:

      【解决方案3】:

      我们可以使用slicematch

      library(dplyr)
      df %>% 
           group_by(subj, trial) %>%
           slice(match('T', type))
      # A tibble: 4 x 4
      # Groups:   subj, trial [4]
      #  subj  trial   fix type 
      #  <chr> <int> <int> <chr>
      #1 a         1     2 T    
      #2 a         2     3 T    
      #3 b         1     1 T    
      #4 b         2     2 T    
      

      数据

      df <- structure(list(subj = c("a", "a", "a", "a", "a", "a", "b", "b", 
      "b", "b", "b", "b"), trial = c(1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 
      1L, 2L, 2L, 2L), fix = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 
      1L, 2L, 3L), type = c("K", "T", "T", "K", "K", "T", "T", "K", 
      "K", "K", "T", "T")), class = "data.frame", row.names = c("1", 
      "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))
      

      【讨论】:

        猜你喜欢
        • 2019-06-05
        • 1970-01-01
        • 2016-07-09
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 2019-08-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多