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?