Recode numeric values in R

a 夏天 提交于 2020-06-22 22:45:28

问题


I want to recode some numeric values into different numeric values and have had a go using the following code:

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

I get the following error:

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

Where am I going wrong?


回答1:


This function does not work on numeric vector. If you want to use it, you can do as follows:

 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



回答2:


We can recode numeric values by using recode or case_when on dplyr 0.7.0.

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



回答3:


Try this:

#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


来源:https://stackoverflow.com/questions/24011836/recode-numeric-values-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!