4

I am trying to compare col with the col_new in my data and create a new boolean identifier called change_col which identifies the changes.

Below is an example:

input <- data.frame(
  apple = c(1,2)
  ,apple_new = c(2,3)
  ,banana = c(1,2)
  ,banana_new = c(1,3)
)

desired_output <- data.frame(
  apple = c(1,2)
  ,apple_new = c(2,3)
  ,change_apple = c(TRUE,TRUE)
  ,banana = c(1,2)
  ,banana_new = c(1,3)
  ,change_banana = c(FALSE,TRUE)
)

I am thinking of using mutate together with across to loop over apple and banana but kind of failed... Anyone has any better idea?

library(dplyr)

var_to_consider <- c('apple','banana')

input %>%
  mutate( across(c(var_to_consider), 
                 .fns = list(change = ~ . != !!sym(paste0(.,'_new') )),
                 .names = "{fn}_{col}" ) )

The above will result the following error:

Error: Only strings can be converted to symbols
Daves
  • 175
  • 1
  • 10

1 Answers1

-1

This can be done with direct comparison.

var <- c('apple','banana')
input[paste0('change_', var)] <- input[var] != input[paste0(var, '_new')]

#  apple apple_new banana banana_new change_apple change_banana
#1     1         2      1          1         TRUE         FALSE
#2     2         3      2          3         TRUE          TRUE
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213