【发布时间】:2021-07-25 08:25:40
【问题描述】:
我有一个大数据框(在一个小样本下方),我需要根据某些条件将所有以相同前缀开头的列转换为多个列,保留原始变量并将原始后缀携带到新变量中。
数据:
egp <= structure(list(EGP_2007 = structure(c("", "", "II", "", "", "", "", "", "V", "VI"), format.sas = "$"),
EGP_2008 = structure(c("", "", "IIIb", "", "", "", "IIIb", "", "V", "VI"), format.sas = "$"),
EGP_2009 = structure(c("", "", "IIIb", "", "", "", "I", "II", "V", "I"), format.sas = "$"),
EGP_2010 = structure(c("", "", "", "", "", "I", "", "II", "V", "I"), format.sas = "$"),
EGP_2011 = structure(c("I", "II", "", "", "", "I", "", "II", "V", "I"), format.sas = "$"),
EGP_2012 = structure(c("I", "II", "", "", "I", "VIIb", "I", "II", "I", "I"), format.sas = "$"),
EGP_2013 = structure(c("I", "II", "", "", "I", "VIIb", "IIIa", "II", "I", "I"), format.sas = "$"),
EGP_2014 = structure(c("I", "II", "", "IIIb", "I", "VIIb", "IIIa", "II", "I", "I"), format.sas = "$"),
EGP_2015 = structure(c("I", "IIIa", "", "IIIb", "I", "VIIb", "IIIa", "II", "I", "I"), format.sas = "$"),
EGP_2016 = structure(c("I", "IIIa", "", "IIIb", "I", "", "IIIa", "IIIa", "I", "I"), format.sas = "$"),
EGP_2017 = structure(c("", "", "", "IIIb", "I", "", "IIIa", "II", "I", "I"), format.sas = "$"),
EGP_2018 = structure(c("", "II", "", "IIIb", "I", "", "IIIa", "IIIa", "I", "IIIb"), format.sas = "$")), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"))
我尝试了什么:
我尝试使用 this SO answer 解决我的问题,但出现以下错误:
Error: Problem with `mutate()` input `..1`. x Can't convert a double vector to function i Input `..1` is `across(...)`.
这是我的代码:
egp_2 <- egp %>%
mutate(across(contains("EGP"),
.fns = list(professional = case_when(. %in% c("I", "II") ~ 1,
. %in% c("IIIa", "IIIb", "V", "VI", "VIIa", "VIIb") ~ 0,
T ~ NA_real_),
routine_non_manual = case_when(. %in% c("IIIa", "IIIb", "V") ~ 1,
. %in% c("I", "II", "VI", "VIIa", "VIIb") ~ 0,
T ~ NA_real_),
manual = case_when(. %in% c("VI", "VIIa", "VIIb") ~ 1,
. %in% c("I", "II", "IIIa", "IIIb", "V") ~ 0,
T ~ NA_real_)),
.names = "{fn}_{col}" ))
感谢任何解决方案。原始变量包含职业分类,我想将其转换为用于绘图和回归的子类型虚拟变量。
【问题讨论】: