【发布时间】: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 <- interaction(df$id, df$year, drop = TRUE)和if (length(unique(df$main[rows])) > 0) -
@akrun:非常感谢。现在可以了。
-
Lisolette,不要为你一直问而道歉……如果你不问,你将得不到答案。我很高兴 akrun 的回答对你有用,我希望你能在那之后迅速前进。 :-)
标签: r loops if-statement