如果某一行符合条件,则删除该类别的所有行

Kir*_*ier 5 r subset dataframe

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

练习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)
)
Run Code Online (Sandbox Code Playgroud)

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

   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
Run Code Online (Sandbox Code Playgroud)

我想删除所有主题2,因为该行的fixations列的值为0,而ias的值为A。但是,我希望不删除主题3而这样做,因为即使有0,它也是在ias列的值为B的行中。

到目前为止我的尝试。

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

但是,缺少了仅在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
Run Code Online (Sandbox Code Playgroud)

非常感谢你!

相关问题:

R:根据几列中的值从数据框中删除行

当只有一行满足R中的条件时,如何删除属于特定组的所有行?

akr*_*run 5

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

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
Run Code Online (Sandbox Code Playgroud)

all|

df1 %>%
   group_by(subj) %>%
   filter(all(fixations!=0 | ias !="A"))
Run Code Online (Sandbox Code Playgroud)

同样的方法也与使用avebase R

df1[with(df1, !ave(fixations==0 & ias =="A", subj, FUN = any)),]
Run Code Online (Sandbox Code Playgroud)

数据

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"))
Run Code Online (Sandbox Code Playgroud)