Home > Back-end >  how to check if a different values are greater than different data frame rows in R?
how to check if a different values are greater than different data frame rows in R?

Time:09-22

I have a data frame

df1   =data.frame(a=c(100,200,150,NA),
                 b=c(300,40,90,30),
                 c=c(12,500,1000,2))

df2 = data.frame(s= c(150,300,80,15))

I need to check whether the values of df1 are greater than df2$s wrt rows.
For ex. 150 will be compared to 1st row i.e. (100,300,12) of df will result in (F, T, F).
Similarly 300 to 2nd row and so on

Required Output

result_df =  data.frame(a=c(F,F,T,F),
                        b=c(T,F,T,T),
                        c=c(F,T,T,F))
   

it can be done in the loop, but is there any faster approach?

CodePudding user response:

We can replicate to make the lengths same and do the comparison

df1 > df2[row(df1)] & !is.na(df1)

-output

      a     b     c
[1,] FALSE  TRUE FALSE
[2,] FALSE FALSE  TRUE
[3,]  TRUE  TRUE  TRUE
[4,] FALSE  TRUE FALSE

Or may also extract the column from 'df2' and directly do the comparison

df1 >df2$s & !is.na(df1)
  • Related