Displaying Rows conditional on values of two columns - R

Viewed 120
treat age education black hispanic married nodegree re74 re75
1: 0 23 10 1 0 0 1 0
2: 0 26 12 0 0 0 0 0
3: 0 22 9 1 0 0 1 0
4: 0 18 9 1 0 0 1 0

I'm trying to only display data where either re74==0 or re75==0 or both are equal to zero, which implies that I'm disregarding the rows where both are equal to one.

3 Answers

You can use filter from dplyr

library(dplyr)
df %>% filter(re74 == 0 | re75 == 0)
(¬_¬)df <- data.frame(
...   stringsAsFactors = FALSE,
...              treat = c("1:", "2:", "3:", "4:"),
...                age = c(0L, 0L, 0L, 0L),
...          education = c(23L, 26L, 22L, 18L),
...              black = c(10L, 12L, 9L, 9L),
...           hispanic = c(1L, 0L, 1L, 1L),
...            married = c(0L, 0L, 0L, 0L),
...           nodegree = c(0L, 0L, 0L, 0L),
...               re74 = c(1L, 0L, 1L, 1L),
...               re75 = c(1L, 0L, 0L, 0L)
... )
(¬_¬)df[df$re74==0 |df$re75==0, ]
  treat age education black hispanic married nodegree re74 re75
2    2:   0        26    12        0       0        0    0    0
3    3:   0        22     9        1       0        0    1    0
4    4:   0        18     9        1       0        0    1    0

We can use subset

 subset(df, re74 == 0 | re75 == 0)
Related