Question:
Let's suppose we have a data.frame
like the following:
set.seed(2019)
datos <- data.frame(ANO1=sample(1:10, 10, replace = TRUE),
ANO2=sample(1:10, 10, replace = TRUE))
datos
ANO1 ANO2
1 8 8
2 8 7
3 4 3
4 7 2
5 1 7
6 1 7
7 9 1
8 1 8
9 2 4
10 7 5
What I am looking for is to create a matrix with the logical value of comparing if the two columns are less than a certain set of numbers, for example, let's say a range from 1 to 10, taking as reference the first row, I would like to obtain something like this :
ANO1 ANO2 1 2 3 4 5 6 7 8 9 10
1 8 8 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE
In this case the two 8
's are less than 10
and 9
but not less than the rest of the values.
Answer:
One way that occurs to me is to create a reference matrix to compare, that is, we are going to create a matrix with the 10 "comparables" and the number of rows of the data.frame
, that is:
nr <- nrow(datos)
mref <- matrix(rep(1:10, nr), nrow = nr , byrow = TRUE)
mref
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1 2 3 4 5 6 7 8 9 10
[2,] 1 2 3 4 5 6 7 8 9 10
[3,] 1 2 3 4 5 6 7 8 9 10
[4,] 1 2 3 4 5 6 7 8 9 10
[5,] 1 2 3 4 5 6 7 8 9 10
[6,] 1 2 3 4 5 6 7 8 9 10
[7,] 1 2 3 4 5 6 7 8 9 10
[8,] 1 2 3 4 5 6 7 8 9 10
[9,] 1 2 3 4 5 6 7 8 9 10
[10,] 1 2 3 4 5 6 7 8 9 10
Having this, and thanks to the fact that the comparisons are actually functions, we could individually compare each column with its reference value:
a <- `<`(datos$ANO1, mref)
b <- `<`(datos$ANO2, mref)
Note: I originally thought it wouldn't work, but it's totally okay to do:
a <- datos$ANO1 < mref
b <- datos$ANO2 < mref
And now we simply make sure that both columns are less than the reference value with an &
(array logical and
), the combination of the results is only for the purpose of verifying the results:
cbind(datos, a & b)
ANO1 ANO2 1 2 3 4 5 6 7 8 9 10
1 8 8 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE
2 8 7 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE
3 4 3 FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE
4 7 2 FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE
5 1 7 FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE
6 1 7 FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE
7 9 1 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE
8 1 8 FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE
9 2 4 FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE TRUE
10 7 5 FALSE FALSE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE