我有以下代码...
pMiss <- function(x){sum(is.na(x))}
missing_values_data <- apply(csv,1,pMiss)
但这只会输出类似...
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[2] 0 0 0 0 0 0 0 0 20 0 0 0 0 0 0 0 0
[3] 0 0 0 0 10 0 0 0 0 0 0 0 0 0 0 0 0
[4] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
[5] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
10和20是包含NA的行。有没有一种方法可以输出这些行在数据帧中的索引位置,例如[3,5]等。
答案 0 :(得分:0)
sapply(df, function(x){which(is.na(x))})
# Data Used:
df <- data.frame(x1 = c(84.2,105.2,79.2,NA,108.2,79.2,112.2,NA,114.2,92.2),
x2 = c(138.3,110.3,84.3,45.3,128.3,99.3,NA,124.3,121.3,115.3),
x3 = as.character(c(138.3,110.3,84.3,45.3,128.3,99.3,100.3,124.3,121.3,115.3)),
stringsAsFactors = FALSE)
答案 1 :(得分:0)
您可以在which函数中使用参数arr.ind
返回数组索引。简短示例
df <- as.data.frame(matrix(rnorm(1000), ncol = 10, nrow = 100))
df[1,3] <- NA
df[3,9] <- NA
which(is.na(df), arr.ind = TRUE)
row col
[1,] 1 3
[2,] 3 9
我想念这个问题,如果您只对行感兴趣,那么只需提取正确的列即可
> which(is.na(df), arr.ind = TRUE)[ ,1]
[1] 1 3