Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
按行值必须为TRUE的一组列筛选data.frame_R_Filter - Fatal编程技术网

按行值必须为TRUE的一组列筛选data.frame

按行值必须为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 <

这是重现我的错误的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

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]))
不清楚你的函数应该做什么,在这种情况下你不会得到一个空的数据集。但是,这里的整个方法似乎可以归结为某种类型的a
rowSums
没有循环的一行程序。可能
行和(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
}