如果语句'参数的长度为零'则出现R错误[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我写了三个函数,其中两个函数(即function1和function2)用于populatedataset的另一个函数。

当我收到Error in if (num == 1) { : argument is of length zero的错误时,我正在运行populatedataset函数

我认为这是由于'if(num == 1){:'部分导致的function2。

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)
}

我一直在阅读其他页面上的这个错误,但我似乎无法找到与此问题相关的解决方案。

我非常感谢对此错误的任何见解!

r function if-statement
1个回答
0
投票

if条件必须是TRUEFALSE。这个错误暗示num == 1评估为logical(0)。这可能是因为num是空的,即numeric(0),因为那时你正在比较长度0到1的数值,它给出了长度为0的逻辑。你可以用num == 1函数包装你的条件isTRUE,这将把logical(0)变成一个FALSE

if (isTRUE(num == 1)){....

函数isTRUE检查参数是否为逻辑值TRUE。由于在这种情况下num == 1logical(0)isTRUE将返回FALSE并且if按照惯例工作。

旁注:numnumeric(0)is可能是因为person == as.character(personindex)不是任何人的TRUE,所以如果你索引你的表没有返回newpersonality值。在这种情况下,如果您使用我的解决方案,您将遇到else-if构造的else部分。

© www.soinside.com 2019 - 2024. All rights reserved.