Vish
Vish

Reputation: 39

How to remove rows conditionally in R?

I want to remove certain group of rows, if the condition matched. For example

Group  X1  X2  X3
1      0.2  1   2
1      0.8  2   4
1      0.0  1   2
2      0.4  1   3
2      0.2  2   3
2      0.3  2   4
2      0.1  1   2
3      0.5  4   2
3      0.4  1   2
3      0.1  3   1

Suppose I want to delete group-1 as it contains value '0' for x1. How to delete.

Upvotes: 3

Views: 9077

Answers (3)

talat
talat

Reputation: 70336

You can do it easily in base R and without grouping like this:

# check in which groups X1 == 0 appears:
groups_to_remove <- unique(df$Group[df$X1 == 0])
# just to double check the result:
groups_to_remove
#[1] 1
# remove those groups from data:
df[!df$Group %in% groups_to_remove, ]
#   Group  X1 X2 X3
#4      2 0.4  1  3
#5      2 0.2  2  3
#6      2 0.3  2  4
#7      2 0.1  1  2
#8      3 0.5  4  2
#9      3 0.4  1  2
#10     3 0.1  3  1

If you prefer a "one-liner", you can use for example:

subset(df, !Group %in% unique(Group[X1 == 0]))
#   Group  X1 X2 X3
#4      2 0.4  1  3
#5      2 0.2  2  3
#6      2 0.3  2  4
#7      2 0.1  1  2
#8      3 0.5  4  2
#9      3 0.4  1  2
#10     3 0.1  3  1

Upvotes: 1

TPArrow
TPArrow

Reputation: 1584

use data.matrix() first and then use matrix filtering

x=data.matrix(your data)
x[-((x[,1]==1) & (x[,2]==0)),]

Upvotes: 0

akrun
akrun

Reputation: 887971

We can use data.table

library(data.table)
setDT(df1)[,  if(!any(!X1)) .SD,by = Group]

Or using dplyr

library(dplyr)
df1 %>%
     group_by(Group) %>%
     filter(!any(!X1))

Upvotes: 3

Related Questions