【问题标题】:R error if statement 'argument is of length zero' [duplicate]如果语句'参数长度为零',则R错误[重复]
【发布时间】:2018-11-10 07:01:19
【问题描述】:

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

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

我认为这是由于 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)
}

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

我将不胜感激任何对此错误的见解!

【问题讨论】:

标签: r function if-statement


【解决方案1】:

if 条件必须是 TRUEFALSE。此错误暗示num == 1 的计算结果为logical(0)。这可能是由于num 为空(即numeric(0))引起的,因为此时您将长度为 0 的数值与 1 进行比较,得出长度为 0 的逻辑值。您可以将条件 num == 1 包装为 isTRUElogical(0) 变成FALSE 的函数:

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

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

旁注:num 成为numeric(0) 可能是由于person == as.character(personindex) 不是TRUE 对任何人而言,因此如果您为表编制索引,则不会返回newpersonality 值。在这种情况下,如果您使用我的解决方案,您将遇到 if-else-construct 的 else 部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多