这是重现我的错误的MWE:
df <- data.frame(
col1 = c(TRUE, FALSE, FALSE),
col2 = c(FALSE, TRUE, FALSE),
col3 = c(FALSE, FALSE, TRUE),
col4 = c(TRUE, FALSE, TRUE)
)
filterByTrueCols <- function(df, trueCols) {
for (rule in trueCols) {
df <- df[df[rule] == TRUE,]
}
df
}
filterByTrueCols(df, c("col1", "col2", "col4"))
>> Error in matrix(unlist(value, recursive = FALSE, use.names = FALSE), nrow = nr, :
length of 'dimnames' [2] not equal to array extent
然而,这个修改解决了我的问题:
filterByTrueCols <- function(df, trueCols) {
for (rule in trueCols) {
# inserted to prevent error,
# result should be the same since filtering makes sense only when there are rows
if(nrow(df)) {
df <- df[df[rule] == TRUE,]
}
}
df
}
我知道提出多个问题不是好习惯,但在这种情况下:为什么会弹出错误,是否有更好的方法来实现我想要实现的目标?
编辑:在这种情况下,预期的输出是一个空的data.frame,因为没有满足条件的行。