[英]Use a list of variables and levels to convert character data to factors using dplyr
I'm working with survey data and I need to code the response values as factors (eg Strongly disagree, disagree, agree, Strongly agree).我正在处理调查数据,我需要将响应值编码为因素(例如,非常不同意、不同意、同意、非常同意)。 Different questions have different response options and need to be coded appropriately.不同的问题有不同的回答选项,需要适当地编码。 I have an excel file that lists every question and the ordered response options.我有一个 excel 文件,其中列出了每个问题和有序的响应选项。 I've written a for
loop to convert all the variables, but would like to understand how to do it with purrr
or dplyr
syntax.我已经编写了一个for
循环来转换所有变量,但想了解如何使用purrr
或dplyr
语法来做到这一点。
Here is a simple example:这是一个简单的例子:
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
It can be有可能
map2_dfc(factor_map2$var, factor_map2$levels,
~ factor(dat[[.x]], levels = .y))%>%
setNames(factor_map2$var)
Or another option without using any new package ie with only dplyr is或者不使用任何新的 package 的另一个选项,即只有 dplyr 是
dat %>%
mutate(across(all_of(factor_map2$var), ~ factor(., levels =
factor_map2$levels[match(cur_column(), factor_map2$var)])))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.