我有这样的数据框:
df <- data.frame(col1 = c(letters[1:4],"a"),col2 = 1:5,col3 = letters[10:14])
df
col1 col2 col3
1 a 1 j
2 b 2 k
3 c 3 l
4 d 4 m
5 a 5 n
Run Code Online (Sandbox Code Playgroud)
我想找到列的索引,其df值与字符串"a"匹配.即它应该给我1结果.我尝试使用它在sapply但它不工作.任何人都知道怎么做没有循环?
joh*_*nes 13
像这样的东西?
which(apply(df, 2, function(x) any(grepl("a", x))))
Run Code Online (Sandbox Code Playgroud)
步骤是:
apply每一栏a在此列中greplany用来获取TRUE是否匹配了任何元素awhich元素(列)是TRUE(即包含搜索到的字母a).既然您提到您尝试使用sapply()但未成功,那么您可以这样做:
> sapply(df, function(x) any(x == "a"))
col1 col2 col3
TRUE FALSE FALSE
> which(sapply(df, function(x) any(x == "a")))
col1
1
Run Code Online (Sandbox Code Playgroud)
当然,如果您更喜欢字符串匹配,也可以使用grep()/grepl()方法。如果您只需要列号,您也可以将您的which()函数包装起来unname()。