我正在处理调查数据,需要将响应值编码为因子(例如:非常不同意、不同意、同意、非常同意)。不同的问题有不同的响应选项,需要适当编码。我有一个Excel文件,列出了每个问题和有序的响应选项。我已经编写了一个for循环来转换所有变量,但希望了解如何使用purrr或dplyr语法来完成它。
以下是一个简单的示例:
以下是一个简单的示例:
library(tidyverse)
dat <- iris %>%
mutate(
Species = as.character(Species),
second_var = as.character(round(Sepal.Length)))
factor_map <- data.frame(
var = c("Species", "second_var"),
response_opts = c("setosa,versicolor,virginica",
"4,5,6,7,8"))
# convert character string of options into lists
factor_map2 <- factor_map %>%
mutate(levels = str_split(response_opts, ","))
# simple for loop
dat2 <- dat
for (i in 1:nrow(factor_map2)) {
v <- factor_map2$var[i]
l <- factor_map2$levels[[i]]
dat2[[v]] = factor(dat2[[v]], levels = l)
rm(v, l)
}
# How to use factor_map to convert the columns in dat to factors?
# map2 doesn't seem to work, unclear why it says .x has length of 6
dat %>%
map2(factor_map2$var, factor_map2$levels,
function(x, y) factor(x, levels = y))
# Can I pass a vector of variable specific levels into across?
dat %>%
mutate(across(factor_map2$var, factor, # somehow pass in the levels