簡體   English   中英

使用變量和級別列表將字符數據轉換為使用 dplyr 的因子

[英]Use a list of variables and levels to convert character data to factors using dplyr

我正在處理調查數據,我需要將響應值編碼為因素(例如,非常不同意、不同意、同意、非常同意)。 不同的問題有不同的回答選項,需要適當地編碼。 我有一個 excel 文件,其中列出了每個問題和有序的響應選項。 我已經編寫了一個for循環來轉換所有變量,但想了解如何使用purrrdplyr語法來做到這一點。

這是一個簡單的例子:

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

有可能

map2_dfc(factor_map2$var, factor_map2$levels, 
      ~ factor(dat[[.x]], levels = .y))%>%
   setNames(factor_map2$var)

或者不使用任何新的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM