如何根据 R 中的 if 条件语句重新编码一组变量中的负值?
How to recode negative values in a set of variables based on if conditional statement in R?
这里是R新手。我目前正在尝试重新编码 R 中的一组变量,以便将其中的所有负值重新编码为正值。
请在下面找到模拟数据:
df <- data.frame(ID = c(1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011),
measure1 = rnorm(11, mean = 0, sd = 1),
measure2 = rnorm(11, mean = 0, sd = 1),
measure3 = rnorm(11, mean = 0, sd = 1),
measure4 = rnorm(11, mean = 0, sd = 1))
这是我目前编写的函数:
df[2:5] <- sapply(df[2:5], function(x) {
if(x<0) {
return(x*-1)
} else {
return(x)
}
})
虽然我收到以下错误:
Warning messages:
1: In if (x < 0) { :
the condition has length > 1 and only the first element will be used
2: In if (x < 0) { :
the condition has length > 1 and only the first element will be used
3: In if (x < 0) { :
the condition has length > 1 and only the first element will be used
4: In if (x < 0) { :
the condition has length > 1 and only the first element will be used
关于如何使这项工作有任何想法吗?
谢谢!
您可以使用
df[, 2:5] <- abs(df[, 2:5])
这里是R新手。我目前正在尝试重新编码 R 中的一组变量,以便将其中的所有负值重新编码为正值。
请在下面找到模拟数据:
df <- data.frame(ID = c(1001, 1002, 1003, 1004, 1005, 1006, 1007, 1008, 1009, 1010, 1011),
measure1 = rnorm(11, mean = 0, sd = 1),
measure2 = rnorm(11, mean = 0, sd = 1),
measure3 = rnorm(11, mean = 0, sd = 1),
measure4 = rnorm(11, mean = 0, sd = 1))
这是我目前编写的函数:
df[2:5] <- sapply(df[2:5], function(x) {
if(x<0) {
return(x*-1)
} else {
return(x)
}
})
虽然我收到以下错误:
Warning messages:
1: In if (x < 0) { :
the condition has length > 1 and only the first element will be used
2: In if (x < 0) { :
the condition has length > 1 and only the first element will be used
3: In if (x < 0) { :
the condition has length > 1 and only the first element will be used
4: In if (x < 0) { :
the condition has length > 1 and only the first element will be used
关于如何使这项工作有任何想法吗?
谢谢!
您可以使用
df[, 2:5] <- abs(df[, 2:5])