R在多个数据帧列中查找值 [英] R find value in multiple data frame columns

查看:80
本文介绍了R在多个数据帧列中查找值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个数据集,其中数值可能位于数据框中的一组列中:

Given a data set where a value could be in any of a set of columns from the dataframe:

df <- data.frame(h1=c('a', 'b', 'c', 'a', 'a', 'b', 'c'), h2=c('b', 'c', 'd', 'b', 'c', 'd', 'b'), h3=c('c', 'd', 'e', 'e', 'e', 'd', 'c'))

如何获取指定哪些行包含目标值的逻辑向量?在这种情况下,搜索'b',我想要一个逻辑向量与行(1,2,4,6,7)为TRUE。

How can I get a logical vector that specifies which rows contain the target value? In this case, searching for 'b', I'd want a logical vector with rows (1,2,4,6,7) as TRUE.

真正的数据集要大得多,更复杂,所以我试图避免一个for循环。

The real data set is much larger and more complicated so I'm trying to avoid a for loop.

感谢

编辑:

这似乎很有效。

>apply(df, 1, function(x) {'b' %in% as.vector(t(x))}) -> i
> i
[1]  TRUE  TRUE FALSE  TRUE FALSE  TRUE  TRUE


推荐答案

如果速度是一个问题,我会去:

If speed is a concern I would go with:

rowSums(df == "b") > 0

这篇关于R在多个数据帧列中查找值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆