假设我们有以下数据框:
> dataset1
x
1 1
2 2
3 3
4 NA
5 5
我希望能够编写一个R命令,计算包含“NA”值的单列数据框的行索引。更具体地说,在上面的dataset1示例中,这样的命令将返回4——因为'NA'出现在数据框的第4行。我该如何实现?谢谢!
正如Ben Bolker所建议的那样,可以同时使用which
和is.na
,例如:
> which(is.na(dataset1), arr.ind=TRUE)
row col
4 4 1 # NA is in row 4 and column 1
which(is.na(dataset1[[1]]))
。 - Ben Bolker使用 tidyverse
生态系统中的函数的另一种方法:
> dataset1 %>%
rowid_to_column() %>%
filter(is.na(x))
rowid x
1 4 NA
newdataset1
的数据表,该表是由从dataset1
中删除具有缺失列值的行形成的。使用-which(is.na)
。 newdataset1<-dataset1[-which(is.na(dataset1$x)),]
your_dataframe[unique(which(is.na(your_dataframe), arr.ind=TRUE)[,1]),]
或者使用dplyr:
your_dataframe %>%
dplyr::setdiff(., na.omit(.))
?which
,?is.na
等相关文档。 - Ben Bolker