Recode numeric values in R

前端 未结 3 386
一向
一向 2021-01-12 18:09

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

3条回答
  •  醉梦人生
    2021-01-12 18:54

    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
    

提交回复
热议问题