B C - 11 months ago 46

R Question

Hypothetical data:

`a <- c(400,500,600,700,100,600,700,100)`

b <- c(2,2,1,2,2,1,2,1)

c <- c('NA','R','NA','G','NA','R','NA','G')

data <- data.frame(a,b,c)

Output:

`a b c`

1 400 2 NA

2 500 2 R

3 600 1 NA

4 700 2 G

5 100 2 NA

6 600 1 R

7 700 2 NA

8 100 1 G

You can easily subset if it is in the same row:

`subset(data, b== '1' & c =='R')`

Output:

`a b c`

6 600 1 R

My question is how do I subset between rows? For example, how do I find all values of c = 'R' when b = '2' on the above row?

`a b c`

2 500 1 R

6 600 1 R

Answer Source

How do I find all values of

`c = 'R'`

when`b = '2'`

on the above row?

How about

```
b2above <- which(data$b == 2) + 1L
cR <- which(data$c == "R")
id <- cR[cR %in% b2above] ## or `id <- intersect(cR, b2above)`
data[id, ]
# a b c
#2 500 2 R
#6 600 1 R
```