我想根据特定值识别列名和索引。这是我的示例数据框 -
set.seed(1)
age_range = sample(c("ar2-15", "ar16-29", "ar30-44"), 200, replace = TRUE)
gender = sample(c("M", "F",-999), 200, replace = TRUE)
region = sample(c("A", "B", "C"), 200, replace = TRUE)
physi = sample(c("Poor", "Average", "Good"), 200, replace = TRUE)
height = sample(c(4,5,6,-999), 200, replace = TRUE)
height2 = sample(c(40,0), 200, replace = TRUE)
weight2 = sample(c(20,0,-999), 200, replace = TRUE)
survey = data.frame(age_range, gender, region,physi,height,height2,weight2)
head(survey)
如何在调查df中找到-999存在的列名称和索引?我尝试使用apply的哪些组合,但是它没有用。显然我做错了什么。
编辑:
> apply(survey,2,function(x) match(-999,x))
age_range gender region physi height height2 weight2
NA 10 NA NA 1 NA 2
这只给出了所有列名,并显示了没有-999的列的NA。任何指针都非常感谢。谢谢! 珍
答案 0 :(得分:2)
根据d.b。的评论,我创建了这一短代码,它可以满足我的需要。谢谢Stackoverflow社区!
q=unique(data.frame(which(survey == -999, arr.ind = TRUE))[2])[1]$col
q # 2 5 7
names(survey[,q]) # [1] "gender" "height" "weight2"
答案 1 :(得分:1)
lappply
which
能为您提供所需内容吗?它将返回列名列表,其中每个项都包含该元素= -999
lapply(survey,function(x) which(x==-999))