【问题标题】:Recode numeric values in R在 R 中重新编码数值
【发布时间】:2014-07-23 14:12:51
【问题描述】:

我想将一些数值重新编码为不同的数值,并尝试使用以下代码:

survey$KY27PHYc <- revalue(survey$KY27PHY1, c(5=3, 4=2,3=2,2=1,1=1))

我收到以下错误:

## Error: unexpected '=' in "survey$KY27PHYc <- revalue(survey$KY27PHY1, c(5="

我哪里错了?

【问题讨论】:

  • 您是否为此使用plyr?你可能应该提到它
  • 哎呀,不知道它是怎么进来的。复制和粘贴时出错。
  • Ash,请告诉我们哪个你指的是'revalue()'!使用 search() 或 ?revalue 来解决这个问题。 (我假设它是 dplyr,我简要地标记了它。)
  • 您也可以尝试 merge 使用包含新旧值的数据框:merge(survey, data.frame(KY27PHY1 = c(5,4,3,5,1), KY27PHY1_new = c(3,2,2,1,1)))

标签: r numeric recode


【解决方案1】:

我们可以在dplyr 0.7.0 上使用recodecase_when 重新编码数值。

library(dplyr)
packageVersion("dplyr")
# [1] ‘0.7.0’

x <- 1:10

# With recode function using backquotes as arguments
dplyr::recode(x, `2` = 20L, `4` = 40L)
# [1]  1 20  3 40  5  6  7  8  9 10

# Note: it is necessary to add "L" a numerical value.
dplyr::recode(x, `2` = 20, `4` = 40)
# [1] NA 20 NA 40 NA NA NA NA NA NA
# Warning message:
# Unreplaced values treated as NA as .x is not compatible. Please specify replacements exhaustively or supply .default

# With recode function using characters as arguments
as.numeric(dplyr::recode(as.character(x), "2" = "20", "4" = "40"))
# [1]  1 20  3 40  5  6  7  8  9 10

# With case_when function
dplyr::case_when(
  x %in% 2 ~ 20,
  x %in% 4 ~ 40,
  TRUE ~ as.numeric(x)
)
#  [1]  1 20  3 40  5  6  7  8  9 10

【讨论】:

    【解决方案2】:

    此函数不适用于数值向量。如果你想使用它,你可以这样做:

     x <- 1:10 # your numeric vector
    
     as.numeric(revalue(as.character(x), c("2" = "33", "4" = "88")))
    
     # [1]  1 33  3 88  5  6  7  8  9 10
    

    【讨论】:

      【解决方案3】:

      试试这个:

      #sample data
      set.seed(123); x <- sample(1:5, size = 10, replace = TRUE)
      
      x
      # [1] 2 4 3 5 5 1 3 5 3 3
      
      #recode
      x <- c(1, 1, 2, 2, 3)[ x ]
      
      x
      # [1] 1 2 2 3 3 1 2 3 2 2
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-08
        • 2022-07-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多