【问题标题】:How do I recode multiple variables from string to numeric?如何将多个变量从字符串重新编码为数字?
【发布时间】:2021-10-06 09:48:45
【问题描述】:

我正在尝试将字符串变量(例如“没有时间”、“有时”、“经常”...)中的多列数据重新编码为数值(例如“没有时间”= 0)。我已经看到许多对类似问题的不同回复,但是当我尝试这些时,他们似乎删除了所有数据并将其替换为 NA

For_Analysis <- data.frame(Q11_1=c("None of the time", "Often", "Sometimes"),
 Q11_2=c("Sometimes", "Often", "Never"), Q11_3=c("Never", "Never", "Often"))

For_Analysis <- For_Analysis%>% 
  mutate_at(c("Q11_1", "Q11_2", "Q11_3"), 
            funs(recode(., "None of the time"=1,  "Rarely"=2,
                        "Some of the time"=3, "Often"=4, "All of the time"=5)))

当我运行第二段代码时,我得到以下输出

## There were 14 warnings (use warnings() to see them)

并且数据帧中的所有数据都被重新编码为NA,而不是我想要的数值。

【问题讨论】:

  • 你在找FA &lt;- ifelse(test = "None of the time", yes = 1, no = ifelse(test = "Rarely", 2, no = ifelse(...)))

标签: r database dplyr recode


【解决方案1】:

您收到错误消息,因为有些值不匹配。您也可以将mutate_at 替换为across

library(dplyr)

For_Analysis <- For_Analysis%>% 
  mutate(across(starts_with('Q11'), ~recode(., "None of the time"=1,  "Rarely"=2,
                        "Sometimes"=3, "Often"=4, "All of the time"=5, "Never" = 1)))

For_Analysis

#  Q11_1 Q11_2 Q11_3
#1     1     3     1
#2     4     4     1
#3     3     1     4

我冒昧地假设"Never""None of the time" 相同并且编码为1。

【讨论】:

  • 感谢您指出不匹配的值,我已经运行了您在此处建议的代码,不幸的是它仍然将所有数据替换为 NA。
  • 正如我在回答中所表明的那样,您共享的数据不会发生这种情况。如果您在其他数据上使用此答案,请提供该数据以便我检查。另一件要检查的事情是,如果您从 dplyr 包中调用 recode 函数,请尝试指定 dplyr::recode()
【解决方案2】:

以下方法似乎对我的问题有效(将字符串变量重新编码为多列中的数字):

For_Analysis <- data.frame(Q11_1=c("Never", "Often", "Sometimes"),
 Q11_2=c("Sometimes", "Often", "Never"), Q11_3=c("Never", "Never", "Often"))

New_Values <- c(1, 2, 3, 4, 5)
Old_Values <- unique(For_Analysis$Q11_1)

For_Analysis[1:3] <- as.data.frame(sapply(For_Analysis[1:3],
                     mapvalues, from = Old_Values, to = New_Values))

感谢您的帮助!

【讨论】:

    【解决方案3】:

    将其转换为因子类型变量然后再转换为数字的最简单方法。

    library(tidyverse)
    
    For_Analysis <- data.frame(Q11_1=c("None of the time", "Often", "Sometimes"),
                               Q11_2=c("Sometimes", "Often", "Never"), Q11_3=c("Never", "Never", "Often"))
    
    fRecode = function(x) x %>% fct_inorder() %>% as.numeric()
    For_Analysis %>% mutate_all(fRecode)
    

    输出

      Q11_1 Q11_2 Q11_3
    1     1     1     1
    2     2     2     1
    3     3     3     2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多