【问题标题】:(R) How can I recode multiple columns and make them as new columns? [duplicate](R) 如何重新编码多个列并将它们作为新列? [复制]
【发布时间】:2020-08-01 01:41:28
【问题描述】:

我有这样的数据

> data

satface1         satface2               satface3         satface 4 ... satface10
Agree            Disagree               Neutral
Disagree         Strongly Disagree      Strongly Agree
Agree            Disagree               Agree
Neutral          Agree                  Neutral
Strongly Agree   Neutral                Disagree

我想重新编码

Strongly Disagree = 1, Disagree = 2, Neutral = 3, Agree = 4, Disagree = 5 

并将它们设为新列(名称 satface1_re、satface2_re....)我该怎么做?

> data

satface1         satface2               satface3       (satface4...10)  satface1_re satface2_re satface3_re
Agree            Disagree               Neutral                          4           2           3 
Disagree         Strongly Disagree      Strongly Agree                   2           1           5
Agree            Disagree               Agree                            4           2           4
Neutral          Agree                  Neutral                          3           4           3
Strongly Agree   Neutral                Disagree                         5           3           2

【问题讨论】:

    标签: r dplyr recode


    【解决方案1】:

    一个选项是使用factor 重新编码。按所需顺序指定levels,并在across 中用as.integer 强制转换为numeric,并通过更改.names 添加新列

    library(dplyr) # 1.0.0
    lvls <- c("Strongly Disagree", "Disagree", "Neutral", "Agree", "Strongly Agree") 
    data1 <- data %>%
         mutate(across(starts_with('satface'),
            ~ as.integer(factor(., levels = lvls)), .names = "{col}_re"))
    

    或者将recode 与命名为vector 一起使用

    data %>% 
       mutate(across(starts_with('satface'),
         ~ recode(., !!! setNames(1:5, lvls)), .names = "{col}_re"))
    

    数据

    data <- structure(list(satface1 = c("Agree", "Disagree", "Agree", "Neutral", 
    "Strongly Agree"), satface2 = c("Disagree", "Strongly Disagree", 
    "Disagree", "Agree", "Neutral"), satface3 = c("Neutral", "Strongly Agree", 
    "Agree", "Neutral", "Disagree")), class = "data.frame", row.names = c(NA, 
    -5L))
    

    【讨论】:

    • 我正在尝试使用它,我在recode(data, "Agree" = 1) 进行了短暂的试用,但我遇到了错误。
    • @DanielJachetta 你可以试试更新的代码。在您的代码中,recode 应用于整个数据。我在每列上应用的地方,即向量
    • @DanielJachetta 或使用data %&gt;% mutate(across(starts_with('satface'), ~ recode(., Strongly Disagree` = 1, Disagree = 2, Neutral = 3)))`
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 2015-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多