Barranka Barranka - 4 months ago 10
R Question

Check if all values in data frame meet a condition (the condition is a vector)

I have a data frame which looks as follows:

muestra[1:10,2:5]
## X0 X1 X2 X3
## 21129 0 0 0 0
## 34632 0 0 0 0
## 30612 0 0 0 0
## 10687 0 0 1 2
## 44815 0 0 0 1
## 40552 0 0 0 1
## 15311 0 0 0 0
## 33960 0 0 0 0
## 24073 0 0 0 0
## 13077 0 0 0 0


I'm comparing the rows for a particular vector of values:

muestra[1:10,2:5] == c(0,0,0,0)
## X0 X1 X2 X3
## 21129 TRUE TRUE TRUE TRUE
## 34632 TRUE TRUE TRUE TRUE
## 30612 TRUE TRUE TRUE TRUE
## 10687 TRUE TRUE FALSE FALSE
## 44815 TRUE TRUE TRUE FALSE
## 40552 TRUE TRUE TRUE FALSE
## 15311 TRUE TRUE TRUE TRUE
## 33960 TRUE TRUE TRUE TRUE
## 24073 TRUE TRUE TRUE TRUE
## 13077 TRUE TRUE TRUE TRUE


The value of the comparisson vector might change; i.e. it can be
c(0,0,1,0)
,
c(1,2,1,2)
, etcetera.

I'd like to check if the full row meets the condition; Is there a function that returns something like this:

some_function(muestra[1:10,2:5], c(0,0,0,0))
## some_function(muestra[1:10,2:5], c(0,0,0,0))
## 21129 TRUE
## 34632 TRUE
## 30612 TRUE
## 10687 FALSE
## 44815 FALSE
## 40552 FALSE
## 15311 TRUE
## 33960 TRUE
## 24073 TRUE
## 13077 TRUE

Answer

You are looking for all(). Apply all() to each row:

apply(muestra[1:10,2:5] == c(0,0,0,0), 1, all)
Comments