【发布时间】:2020-02-18 18:07:16
【问题描述】:
这是一个产生错误的最小可重现示例:
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")
【问题讨论】:
-
那么,您想根据列名修改列吗?
-
如果您使用的是
mutate_at,您似乎需要case_when。但是您也应该显示您的dplyr代码并包含一些示例数据以制作正确的reproducible example -
在未使用 dplyr 函数的情况下对单个列执行函数(列)时出现错误,这就是我没有包含它的原因。我还没有尝试将此功能与 dplyr 一起使用。 @MrFlick
-
@slava-kohut 实际上我提供的样本是一列。让我澄清一下。
-
@Krishna
if()不是矢量化控制流语句。如果我有x<-c(3,10)而我有if(x>5) print("ok"),这将不起作用,因为x有两个值,其中一些值小于5 和一些更大。在这种情况下,一条if语句不起作用。您需要ifelse()或if_else或case_when,因为函数一次对data.frame 的所有行进行操作。
标签: r function logical-operators data-cleaning