Home > Net >  Can you use a for loop within dplyr::case_when()?
Can you use a for loop within dplyr::case_when()?

Time:01-06

Happy new year!

I have a named list with N elements.

The list-element is used to recode an existing vector.

My code is at the moment - hera as an example:

vowels<- c("a","e","i","u")
consonants <- letters[!(letters %in% vowels)]
signs <- c("!",".")

# My named list elment is defind as follows
# in Reality I have a list with more than 20 elements!
Listelement <- list(vowels = vowels, consonants = consonants)

# The variable to recode:
OldVar <- c(vowels,consonants,"","", signs)

# Recoding uses case_when
NewVar = case_when(OldVar == "" ~ "empty",
                   OldVar %in% Listelement[[1]] ~ names(Listelement[1]),
                   OldVar %in% Listelement[[2]] ~ names(Listelement[2]),
                   TRUE ~ "other")

NewVar

Is it possible to loop the 2nd and 3rd line in the case_when?

I thought on something like this:

NewVar2 = case_when(OldVar == "" ~ "empty",
                    for (i in c(1:length(Listelement))) {
                      OldVar %in% Listelement[[i]] ~ names(Listelement[i])
                    },
                    TRUE ~ "other")
NewVar2

But this did not work.

Any ideas?

CodePudding user response:

Instead of trying to loop, you can use forcats::fct_collapse():

library(forcats)

NewVar <- fct_collapse(OldVar,
                       "empty" = "",
                       !!!Listelement,
                       other_level = "other")

NewVar
 [1] "vowels"     "vowels"     "vowels"     "vowels"     "consonants"
 [6] "consonants" "consonants" "consonants" "consonants" "consonants"
[11] "consonants" "consonants" "consonants" "consonants" "consonants"
[16] "consonants" "consonants" "consonants" "consonants" "consonants"
[21] "consonants" "consonants" "consonants" "consonants" "consonants"
[26] "consonants" "empty"      "empty"      "other"      "other"     

Note use of the !!! operator to unpack Listelement inside the function call.

  • Related