在任何列中查找包含一个(或多个)值的行 [英] Finding rows containing a value (or values) in any column

查看:46
本文介绍了在任何列中查找包含一个(或多个)值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个包含多列字符串的数据"表.我们想要找到包含某个值的所有行的索引,或者更好的是,找到几个值之一.然而,列是未知的.

Say we have a table 'data' containing Strings in several columns. We want to find the indices of all rows that contain a certain value, or better yet, one of several values. The column, however, is unknown.

目前我所做的是:

apply(df, 2, function(x) which(x == "M017"))

其中 df =

1 04.10.2009 01:24:51   M017  <NA>  <NA>    NA
2 04.10.2009 01:24:53   M018  <NA>  <NA>    NA
3 04.10.2009 01:24:54   M051  <NA>  <NA>    NA
4 04.10.2009 01:25:06   <NA>  M016  <NA>    NA
5 04.10.2009 01:25:07   <NA>  M015  <NA>    NA
6 04.10.2009 01:26:07   <NA>  M017  <NA>    NA
7 04.10.2009 01:26:27   <NA>  M017  <NA>    NA
8 04.10.2009 01:27:23   <NA>  M017  <NA>    NA
9 04.10.2009 01:27:30   <NA>  M017  <NA>    NA
10 04.10.2009 01:27:32   M017  <NA>  <NA>    NA
11 04.10.2009 01:27:34   M051  <NA>  <NA>    NA

如果我们试图找到多个值,这也适用:

This also works if we try to find more than one value:

apply(df, 2, function(x) which(x %in% c("M017", "M018")))

结果是:

$`1`
integer(0)

$`2`
[1]  1  2 20

$`3`
[1] 16 17 18 19

$`4`
integer(0)

$`5`
integer(0)

然而,处理结果列表是相当乏味的.

However, processing the resulting list of lists is rather tedious.

是否有更有效的方法来查找在任何列中包含一个(或多个)值的行?

Is there a more efficient way to find rows that contain a value (or more) in ANY column?

推荐答案

怎么样

apply(df, 1, function(r) any(r %in% c("M017", "M018")))

如果第 i 行包含其中一个值,则第 i 个元素将为 TRUE,否则为 FALSE.或者,如果您只需要行号,请将上述语句括在 which(...) 中.

The ith element will be TRUE if the ith row contains one of the values, and FALSE otherwise. Or, if you want just the row numbers, enclose the above statement in which(...).

这篇关于在任何列中查找包含一个(或多个)值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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