mel*_*lc1 3 if-statement r function
我编写了三个函数,其中两个函数(即function1和function2 )在populatedataset的另一个函数中使用。
当我收到以下错误时,我正在运行函数populatedatasetError in if (num == 1) { : argument is of length zero
我相信这是由于function2 的'if (num == 1) {: ' 部分造成的。
function2 <- function(data, table, dict) {
personindex <- substr(deparse(substitute(data)), start = 1, stop = 2)
num <- table[person == as.character(personindex)]$newpersonality
if (num == 1) {
proptable <- data %>% inner_join(dict[score == 1]) %>% count(word)
proportion <- sum(proptable$n)/nrow(data)
return(proportion)
}
else {
proptable <- data %>% inner_join(dict[score == 0]) %>% count(word)
proportion <- sum(proptable$n/nrow(data))
return(proportion)
}
}
populatedataset <- function(data, table, dict) {
list_a <- c(function1(data, dict), function2(data, table, dict))
return (list_a)
}
Run Code Online (Sandbox Code Playgroud)
我一直在其他页面上阅读此错误,但似乎找不到与此问题相关的解决方案。
如果您能深入了解此错误,我将不胜感激!
条件if必须是TRUE或FALSE。此错误意味着num == 1计算结果为 a logical(0)。这可能是由于num为空而引起的,即numeric(0),因为此时您正在比较长度为 0 的数值与 1,这给出了长度为 0 的逻辑值。您可以使用将num == 1变为isTRUE的函数logical(0)包装您的条件FALSE:
if (isTRUE(num == 1)){....
Run Code Online (Sandbox Code Playgroud)
该函数isTRUE检查参数是否为逻辑值TRUE。既然在这种情况num == 1下logical(0),isTRUE将返回并按预期FALSE工作if。
旁注:num存在可能是由不适合任何人的numeric(0)事实引起的,因此如果您为表建立索引,则不会返回任何值。在这种情况下,如果您使用我的解决方案,您将遇到-构造的部分。person == as.character(personindex)TRUEnewpersonalityelseifelse