如果某一行符合条件,则删除该类别的所有行 [英] Remove all rows of a category if one row meets a condition
问题描述
问题:
如果某行中的某一行在另一列中具有某个值(类似于下面的链接中的问题),我想删除特定类别的所有行。但是,主要区别在于,我希望它仅在与另一列中的条件匹配时才起作用。
Problem: I want to remove all the rows of a specific category if one of the rows has a certain value in another column (similar to problems in the links below). However, the main difference is I would like it to only work if it matches a criteria in another column.
练习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)
)
所以我的数据框看起来像这样。
So my data frame looks like this.
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的行中。
And I want to remove all of subject 2 because it has a value of 0 for fixations column in a row that ias has a value of A. However I want to do this without removing subject 3, because even though there is a 0 it is in a row where the ias column has a value of B.
我到目前为止的尝试。 / p>
My attempt so far.
new.df <- prac_df[with(prac_df, ave(prac_df$fixations != 0, subj, FUN = all)),]
但是,缺少了仅在ias列中值为A的零件才能删除。我尝试了&或者如果但我觉得我可能不知道有一种聪明干净的方法。
However this is missing the part that will only get rid of it if it has the value A in the ias column. I've attempted various uses of & or if but I feel like there's likely a clever and clean way I just don't know of.
我的目标是制作这样的df。
My goal is to make a df like this.
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
非常感谢!
相关问题:
推荐答案
我们将'subj'分组,然后根据 any
和!
We group by 'subj' and then filter
based on the logical condition created with any
and !
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"))
相同的方法可以用于 base R $ c中的
ave
$ c>
The same approach can be used with ave
from base R
df1[with(df1, !ave(fixations==0 & ias =="A", subj, FUN = any)),]
数据
data
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"))
这篇关于如果某一行符合条件,则删除该类别的所有行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!