r语言 - 逻辑运算符和字符串:函数错误



下面是生成错误的最小可重现示例:

comb3 <- function(x) {
if (x == "Unable to do") {
x = 0
} 
} 

这是我的原始功能:

comb <- function(x) {
if (x == "Unable to do") {
x = 0
} else if (x == "Very difficult to do") {
x = 1
} else if (x == "Somewhat difficult to do") {
x = 2
} else if (x == "Not difficult") {
x = 3
} 
}

我正在尝试在下面采样的列上使用此功能。我收到此错误:

Warning messages:
1: In if (x == "Unable to do") { :
the condition has length > 1 and only the first element will be used
2: In if (x == "Very difficult to do") { :
the condition has length > 1 and only the first element will be used
Here is a sample of what the data in one column looks like:
sample <- c("Unable to do", "Somewhat difficult to do", "Very difficult to do", "Unable to do", "Not difficult","Unable to do","Very difficult to do", "Not difficult", "Unable to do", "Not difficult")        

警告消息很好地描述了代码的问题。if是一个函数,它期望一个长度为一个逻辑向量作为输入。因此,要在向量上使用条件,您应该使用类似ifelse的东西,或者如 MrFlick 所说,使用case_whenmutate_at

使用ifelse的函数的等效版本如下所示:

comb1 <- function(x) {
ifelse(x == "Unable to do", 
0,
ifelse (x == "Very difficult to do",
1,
ifelse(x == "Somewhat difficult to do",
2,
ifelse(x == "Not difficult",
3,
## If not match then NA
NA
)
)
)
)
}

请注意,这很难阅读,因为ifelse调用是链接在一起的。 因此,您可以通过在调用sapply时使用函数的略微修改版本来完成相同的事情来避免这种情况

comb2 <- function(x) {
sapply(x, function(y) {
if (y == "Unable to do") {
0
} else if (y == "Very difficult to do") {
1
} else if (y == "Somewhat difficult to do") {
2
} else if (y == "Not difficult") {
3
}
## USE.NAMES = FALSE means that the output is not named, and has no other effect
}, USE.NAMES = FALSE)
}

您还可以使用因子,这些因子在内部编码为从 1 开始的整数,并且 (ab) 使用它从字符串转换为数字:

comb3 <- function(x) {
fac <- factor(x, 
levels = c(
"Unable to do",
"Very difficult to do",
"Somewhat difficult to do",
"Not difficult"
)
)
as.numeric(fac) - 1
}

这 3 个版本的输出是相同的,并且是一个很好的示例,说明如何在 R 中有很多方法来完成事情。这有时可能是一种诅咒而不是礼物。

sample <- c("Unable to do", "Somewhat difficult to do", "Very difficult to do", "Unable to do", "Not difficult","Unable to do","Very difficult to do", "Not difficult", "Unable to do", "Not difficult")
comb1(sample)
# [1] 0 2 1 0 3 0 1 3 0 3
comb2(sample)
# [1] 0 2 1 0 3 0 1 3 0 3
comb3(sample)
# [1] 0 2 1 0 3 0 1 3 0 3

相关内容

  • 没有找到相关文章

最新更新