2
votes

I want to compare each value of a row of a data.frame to its corresponding value in a vector. Here is an example:

df1 <- matrix(c(2,2,4,8,6,9,9,6,4), ncol = 3)
df2 <- c(5,4,6)

> df1
     [,1] [,2] [,3]
[1,]    2    8    9
[2,]    2    6    6
[3,]    4    9    4

> df2
[1] 5 4 6

The comparison would be, if a value in a row of df1 is smaller than its corresponding value in df2, so row1: 2 < 5, 8 < 5, 9 < 5; row2: 2 < 4, 6 < 4, 6 < 4; row3: 4 < 6, 9 < 6, 4 < 6

> result
     [,1]  [,2]  [,3]
[1,] TRUE FALSE FALSE
[2,] TRUE FALSE FALSE
[3,] TRUE FALSE  TRUE

Is there any way to do this without use of a loop?

Thanks lads!

1

1 Answers

0
votes

We can just do a comparison to create the logical matrix

df1 < df2
#   [,1]  [,2]  [,3]
#[1,] TRUE FALSE FALSE
#[2,] TRUE FALSE FALSE
#[3,] TRUE FALSE  TRUE

The reason why it works is based on the recycling of the vector. So, each elements of the vector 'df2', compares with the first columns 'df1', then goes to the second column and so on.


If the length of the vector is not equal to the number of columns of first dataset, we can replicate the vector

df1 < df2[row(df1)]
#    [,1]  [,2]  [,3]
#[1,] TRUE FALSE FALSE
#[2,] TRUE FALSE FALSE
#[3,] TRUE FALSE  TRUE

Or another option is sweep

sweep(df1, 1, df2, "<")