Newbie Newbie - 2 months ago 5
R Question

Subsetting rows with range of column having same values

In R with a dataframe:

one two three four
1 A A Z Z
2 A A A Z
3 A A A A
4 Z A A A
5 A A A A


I want to extract the subset whose rows have at least one
Z
in column
two : four
. That is:

one two three four
1 A A Z Z
2 A A A Z

Answer

We can use rowSums on a logical matrix (from removing the first column (df[-1] and comparing (==) with "Z") to extract the rows

df1[rowSums(df1[-1]=="Z")>0,]
#  one two three four
#1   A   A     Z    Z
#2   A   A     A    Z
Comments