【问题标题】:Remove all rows of a category if one row meets a condition [duplicate]如果一行满足条件,则删除类别的所有行[重复]
【发布时间】:2017-09-27 02:16:39
【问题描述】:

问题: 如果其中一行在另一列中具有特定值,我想删除特定类别的所有行(类似于下面链接中的问题)。但是,主要区别是我希望它仅在它与另一列中的条件匹配时才有效。

练习 df

prac_df <- data_frame(
subj = rep(1:4, each = 4),
trial = rep(rep(1:4, each = 2), times = 2),
ias = rep(c('A', 'B'), times = 8),
fixations = c(17, 14, 0, 0, 15, 0, 8, 6, 3, 2, 3,3, 23, 2, 3,3)
)

所以我的数据框看起来像这样。

   subj   ias fixations
1     1     A        17
2     1     B        14
3     2     A         0
4     2     B         0
5     3     A        15
6     3     B         0
7     4     A         8
8     4     B         6

并且我想删除所有主题 2,因为它在 ias 的值为 A 的行中的注视列的值为 0。但是我想在不删除主题 3 的情况下执行此操作,因为即使有0 它位于 ias 列值为 B 的行中。

到目前为止我的尝试。

new.df <- prac_df[with(prac_df, ave(prac_df$fixations != 0, subj, FUN = all)),]

但是,这缺少只有在 ias 列中具有值 A 时才会删除它的部分。我尝试了 & 或 if 的各种用法,但我觉得可能有一种我不知道的聪明而干净的方式。

我的目标是制作这样的 df。

   subj   ias fixations
1     1     A        17
2     1     B        14
3     3     A        15
4     3     B         0
5     4     A         8
6     4     B         6

非常感谢!

相关问题:

R: Remove rows from data frame based on values in several columns

How to remove all rows belonging to a particular group when only one row fulfills the condition in R?

【问题讨论】:

    标签: r dataframe subset


    【解决方案1】:

    我们根据使用any! 创建的逻辑条件按“subj”和filter 分组

    library(dplyr)
    df1 %>%
       group_by(subj) %>%
       filter(!any(fixations==0 & ias == "A"))
    #   subj   ias fixations
    #  <int> <chr>     <int>
    #1     1     A        17
    #2     1     B        14
    #3     3     A        15
    #4     3     B         0
    #5     4     A         8
    #6     4     B         6
    

    或者使用all|

    df1 %>%
       group_by(subj) %>%
       filter(all(fixations!=0 | ias !="A"))
    

    同样的方法可以用于ave from base R

    df1[with(df1, !ave(fixations==0 & ias =="A", subj, FUN = any)),]
    

    数据

    df1 <- structure(list(subj = c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L), ias = c("A", 
    "B", "A", "B", "A", "B", "A", "B"), fixations = c(17L, 14L, 0L, 
    0L, 15L, 0L, 8L, 6L)), .Names = c("subj", "ias", "fixations"), 
    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8"))
    

    【讨论】:

      猜你喜欢
      • 2021-06-06
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多