0

I'm trying to use loop through column names in dataframe.

I have a dataset, testset, which has about 100 columns. To simplify, I will call these columns in alphabet, a, b, c, ... and so on.

I made function to mutate values in testset into other value.

mutatefun<-function(i){
  i1<-rlang::quo_name(enquo(i))
  output<-testset%>%mutate(!! i1:=case_when({{i}} %in% c(1)~0,
                                   {{i}} %in% c(2)~50,
                                   {{i}} %in% c(3)~100,
                                   TRUE~NA_real_))
  return(output)
  }

When i ran mutatefun(a), it worked. Now I want to use this function for multiple columns in testset

With help of this post R: looping through column names, I created varlist and ran this code.

varlist<-c("a","c","e","k")

for(i in varlist){
output<-mutatefun({{i}})}

However, it didn't return expected results. Instead, it return column a as NA. I think it might read i as only character, not object in testset.

Would you let me know how to solve this problem?

ESKim
  • 422
  • 4
  • 14

1 Answers1

0

Try using map_dfc with transmute

library(dplyr)

purrr::map_dfc(varlist, ~{
   var <- sym(.x)
   transmute(testset, !!.x := case_when(!!var == 1~0, 
                                        !!var == 2~50, 
                                        !!var == 3~100, 
                                        TRUE~ NA_real_))
})

If you want other columns which are not in varlist, you may add

%>% bind_cols(testset %>% select(-varlist))

at the end of the chain.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213