Maral Dorri
Maral Dorri

Reputation: 478

Comparing two dataframes with a condition

I have two dataframes:

df1 <- data.frame( v1 = c(1,2,3,4), 
                   v2 = c(2, 10, 5, 11), 
                   v3=c(20, 25, 23, 2))  

> df1
  v1 v2 v3 
1  1  2 20  
2  2 10 35  
3  3  5 23  
4  4 11  2  

df2 <- data.frame(v1 = 4,  = 10, v3 = 30)

> df2
  v1 v2 v3 
1  4 10 30 

I want to add a new column that would say "Fail" when df1 is larger than df2 and "Pass" when it is smaller so that the intended results would be:

 > df3
  v1 v2 v3 check
1  1  2 20  Pass
2  2 10 35  Fail
3  3  5 23  Pass
4  4 11  2  Fail

Upvotes: 0

Views: 124

Answers (2)

akrun
akrun

Reputation: 887118

In tidyverse, we can make use of c_across

library(dplyr) # >= 1.0.0
df1 %>% 
    rowwise %>%
    mutate(check = c('Pass', 'Fail')[1 + any(c_across(everything()) >= df2)])
# A tibble: 4 x 4
# Rowwise: 
#     v1    v2    v3 check
#  <dbl> <dbl> <dbl> <chr>
#1     1     2    20 Pass 
#2     2    10    25 Fail 
#3     3     5    23 Pass 
#4     4    11     2 Fail 

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

You can make size of both the dataframes similar and directly compare :

ifelse(rowSums(df1 >= df2[rep(1,length.out = nrow(df1)), ]) == 0, 'Pass', 'Fail')
#[1] "Pass" "Fail" "Pass" "Fail"

Or using Map :

ifelse(Reduce(`|`, Map(`>=`, df1, df2)), 'Fail', 'Pass')
#Other similar alternatives :

#c('Pass', 'Fail')[Reduce(`|`, Map(`>=`, df1[-1], df2[-1])) + 1]
#c('Fail', 'Pass')[(rowSums(mapply(`>=`, df1, df2)) == 0) + 1]

Upvotes: 3

Related Questions