可以在dplyr::case_when()中使用for循环吗?

qmb5sa22  于 2023-01-06  发布在  其他
关注(0)|答案(1)|浏览(119)

新年快乐!
我有一个有N个元素的命名列表。
list-element用于重新编码现有向量。
我的代码是在此刻-赫拉为例:

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

是否可以在case_when中循环第2行和第3行?
我想到了这样的事情:

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

但这并不奏效。
有什么想法吗?

bvhaajcl

bvhaajcl1#

您可以使用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"

注意,在函数调用中使用!!!运算符来解包Listelement

相关问题