使用 R 中的任何 NA 查看所有列名 [英] Viewing all column names with any NA in R
本文介绍了使用 R 中的任何 NA 查看所有列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要获取至少有 1 个 NA 的列的名称.
df<-data.frame(a=1:3,b=c(NA,8,6), c=c('t',NA,7))
我需要得到b,c".
我找到了此代码:
<块引用>sapply(df, function(x) any(is.na(x)))
但我只需要有 NA 的变量.
我试过了:
sapply(df, function(x) colnames(df[,any(is.na(x))]))
但我得到了所有的列名.
解决方案
另一种杂技解决方案(只是为了好玩):
colnames(df)[!complete.cases(t(df))][1] "b" "c"
想法是:获取 A 中至少具有 1 NA 的列等效于获取 t(A) 中至少具有 NA 的行.complete.cases
根据定义(非常有效,因为它只是调用 C 函数)给出没有任何缺失值的行.
I need to get the name of the columns that have at least 1 NA.
df<-data.frame(a=1:3,b=c(NA,8,6), c=c('t',NA,7))
I need to get "b, c".
I found this code:
sapply(df, function(x) any(is.na(x)))
But I need only the variables that have any NA.
I tried this:
sapply(df, function(x) colnames(df[,any(is.na(x))]))
But I get all the column names.
解决方案
Another acrobatic solution (just for fun) :
colnames(df)[!complete.cases(t(df))]
[1] "b" "c"
The idea is : Getting the columns of A that have at least 1 NA is equivalent to get the rows that have at least NA for t(A).
complete.cases
by definition (very efficient since it is just a call to C function) gives the rows without any missing value.
这篇关于使用 R 中的任何 NA 查看所有列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文