gpt4 book ai didi

在 R 中重新编码数值

转载 作者:行者123 更新时间:2023-12-04 22:46:27 25 4
gpt4 key购买 nike

我想将一些数值重新编码为不同的数值,并使用以下代码进行了尝试:
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="

我哪里错了?

最佳答案

我们可以使用 recode 重新编码数值或 case_whendplyr 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

关于在 R 中重新编码数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24011836/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com