R 使用“重新编码”在列中记录多个值;ifelse“;陈述
我不熟悉使用“R”(习惯于使用SPSS),我很难为一个变量重新编码值,因为该变量有多个响应或案例。我试图使用一个“ifelse”函数来实现这一点,但我无法使该函数用于修改变量的两个以上值。我想为具有多个案例的变量重新编码响应。目前,数据包括#的1、2、3、4,我想像这样重新编码这些数字:R 使用“重新编码”在列中记录多个值;ifelse“;陈述,r,if-statement,R,If Statement,我不熟悉使用“R”(习惯于使用SPSS),我很难为一个变量重新编码值,因为该变量有多个响应或案例。我试图使用一个“ifelse”函数来实现这一点,但我无法使该函数用于修改变量的两个以上值。我想为具有多个案例的变量重新编码响应。目前,数据包括#的1、2、3、4,我想像这样重新编码这些数字: (1=0.6) (2=1.2) (3=2.5) (4=1.8) 我试图使用一个“ifelse”函数来实现这一点,但我无法使该函数用于修改特定变量的两个以上不同值 ChildPABase19_test$Pre
- (1=0.6)
- (2=1.2)
- (3=2.5)
- (4=1.8)
ChildPABase19_test$Predilection_1 <- ifelse(ChildPABase19_test$Predilection_1==1, 0.6, ifelse(ChildPABase19_test$Predilection_1==2, 1.2,
ifelse(ChildPABase19_test$Predilection_1==3, 2.5, ifelse(ChildPABase19_test$Predilection_1==4, 1.8))
ChildPABase19\u test$prediction\u 1如果您使用代码,可能更容易看到问题
ChildPABase19_test$Predilection_1 <- ifelse(
ChildPABase19_test$Predilection_1 == 1,
0.6,
ifelse(
ChildPABase19_test$Predilection_1 == 2,
1.2,
ifelse(
ChildPABase19_test$Predilection_1 == 3,
2.5,
ifelse(
ChildPABase19_test$Predilection_1 == 4,
1.8
)
)
如果您需要进一步的帮助,中的示例在解释语法方面做得相当好。我认为使用dplyr
包的这段代码可能会有帮助:
require(dplyr)
x = c(1, 2, 3, 4)
transform_rule <- list(
"1" = "0.6",
"2" = "1.2",
"3" = "2.5",
"4" = "1.8"
)
x_recoded <- as.numeric(recode(x, !!!transform_rule))
require(dplyr)
x=c(1,2,3,4)
转换规则最后一个if-else ifelse(ChildPABase19_测试$Prediction_1==4,1.8)缺少else值ifelse(ChildPABase19_测试$Prediction_1==4,1.8,“?”)
library(expss)
ChildPABase19_test = data.frame(Predilection_1 = c(1, 2, 3, 4))
recode(ChildPABase19_test$Predilection_1) = c(1 ~ 0.6, 2 ~ 1.2, 3 ~ 2.5, 4 ~ 1.8)
ChildPABase19_test
# Predilection_1
# 1 0.6
# 2 1.2
# 3 2.5
# 4 1.8