【问题标题】:R argument of length zero in if statementif语句中长度为零的R参数
【发布时间】:2020-08-13 22:50:29
【问题描述】:

我有一个 df

df <- data.frame(id = c(1, 1, 2, 2, 3, 3, 3), 
                 year = c(1997,1997,1997,1997,1998,1998,1998),
                 usable = c(TRUE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE),
                 main = c(TRUE, TRUE, FALSE, FALSE, TRUE, TRUE, TRUE))

当我执行代码时

df$id_year <- interaction(df$id, df$year)
for (i in levels(df$id_year)) {
  rows <- df$id_year == i & df$usable
  if (!unique(df$main[rows]) {
    print("yes")
  }
}

if (!unique(df$main[rows]) 行出现“长度为零的参数”错误。谁能解释一下为什么以及如何解决它?谢谢

【问题讨论】:

  • !unique(df$main[rows] 的意图是什么?它是一个向量,但您似乎将其视为布尔值。
  • Liselotte,我已经mentioned before 表示该特定代码不起作用。你认为unique 会返回什么?试试unique(c(1,1,2,3)) 看看它是(1)不是logical 或者可以这样推断的东西; (2) 根据输出的样子,它不能保证长度为 1。
  • 你需要df$id_year &lt;- interaction(df$id, df$year, drop = TRUE)if (length(unique(df$main[rows])) &gt; 0)
  • @akrun:非常感谢。现在可以了。
  • Lisolette,不要为你一直问而道歉……如果你不问,你将得不到答案。我很高兴 akrun 的回答对你有用,我希望你能在那之后迅速前进。 :-)

标签: r loops if-statement


【解决方案1】:

该问题很可能是由于创建了未使用的levels,因为默认情况下drop = FALSEinteraction

df$id_year <- interaction(df$id, df$year, drop = TRUE)

在循环中,正如其他人提到的那样,!unique( 并不清楚。如果我们检查 lengthunique 元素是否大于 0(if (length(unique(df$main[rows])) &gt; 0),它会打印“yes”

for (i in levels(df$id_year)) {
   rows <- df$id_year == i & df$usable
   if (length(unique(df$main[rows])) > 0) {
     print("yes")
   }
 }
#[1] "yes"
#[1] "yes"
#[1] "yes"

【讨论】:

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