簡體   English   中英

如何將多個變量從字符串重新編碼為數字?

[英]How do I recode multiple variables from string to numeric?

我正在嘗試將多列數據從字符串變量(例如“無時間”、“有時”、“經常”...)重新編碼為數值(例如“無時間”= 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)))

當我運行第二段代碼時,我得到以下 output

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

並且 dataframe 中的所有數據都被重新編碼為NA而不是我想要的數值。

您收到錯誤消息是因為有些值不匹配。 您也可以將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。

以下方法似乎對我的問題有效(將字符串變量重新編碼為多列中的數字):

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))

謝謝您的幫助!

最簡單的方法是將其轉換為 factor 類型的變量,然后再轉換為數字。

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)

output

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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