计算 2 列之一中存在空白的实例数 + r

Count number of instances where a blank exists in one of 2 columns + r

我需要测试数据框以完成记录 - 要使记录完整,必须在两列中都输入一个条目。在下面的示例 df 中,您会看到 9 个条目中的 2 个在其中一行中包含空格。

df <- data.frame(a = c(1,2,"",4,5,6,7,"",8,9),
                 b = c(9,5,2,7,5,"",3,"",6,8))

所需的输出将是 2 or 7 的计数,用于标识完整或相反不完整的记录数。两者均为空白的实例将不计入计数。

可能是 sum 的逻辑 matrix - 将 'df' 转换为逻辑矩阵 (df != ''),得到 rowSums 并检查是否sum (TRUE -> 1 and FALSE -> 0) 等于 return n1 的列数并从总行数中减去得到 n2

n1 <- sum(rowSums(df != '') == ncol(df))
n1
[1] 7
n2 <- nrow(df) - n1
# or if there are some other cases with `NA` etc
n2 <- sum(rowSums(df =='') == 1, na.rm = TRUE)