按行值必须为TRUE的一组列筛选data.frame
这是重现我的错误的MWE:按行值必须为TRUE的一组列筛选data.frame,r,filter,R,Filter,这是重现我的错误的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 <- 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
df意外地将tbl\u df
放在那里。为了避免出现dplyr
,错误仍然存在。预期的输出是什么?请使用一个应该返回一些输出的示例,也许您需要all(df[,1]==df[,2])
并将其与for
循环或使用combn
一起使用,即combn(seq_len(ncol(df1)),2,FUN=function(x)all(df[,x[1]==df[,x[2]))
不清楚你的函数应该做什么,在这种情况下你不会得到一个空的数据集。但是,这里的整个方法似乎可以归结为某种类型的arowSums
没有循环的一行程序。可能行和(df[c(“col1”、“col2”、“col4”))==3
?虽然我甚至不知道你的函数是做什么的。也可以尝试Reduce(`&`,df[c(“col1”、“col2”、“col4”)])
,这样你就不需要知道所选列的数量。
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
}