Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows when they contain certain string using R

Tags:

r

I have a data frame below:

Acct <- c(1001, 1002, 1003)
Tran <- c(01, 02, "ALL")
Group <- c(01, 01, 02)
DF1 <- data.frame(Acct, Tran, Group)

Now I need to select the rows where "ALL" shows up. The result should look like:

 Acct |  Tran  | Group
 1003 |   ALL  |  2

One thing to mention is that "ALL" can be in any column (not just "Tran") and there may be any number of columns.

like image 1000
kzhang12 Avatar asked Mar 14 '26 07:03

kzhang12


2 Answers

You can use DF1 == "ALL" to get a logical matrix to find ALL. Then we can take the rowSums() of that matrix and keep the ones where the sum is not zero.

DF1[rowSums(DF1 == "ALL") != 0, ]
#   Acct Tran Group
# 3 1003  ALL     2
like image 78
Rich Scriven Avatar answered Mar 16 '26 21:03

Rich Scriven


Use this line:

apply(DF1 == "ALL",1,any)

This will result in a T/F vector that corresponds to the rows that contain at least one "ALL"

DF1 == "ALL" gives:

> DF1 == "ALL"
      Acct  Tran Group
[1,] FALSE FALSE FALSE
[2,] FALSE FALSE FALSE
[3,] FALSE  TRUE FALSE

By using apply, as stated above, you get:

> apply(DF1 == "ALL",1,any)
[1] FALSE FALSE  TRUE

And if you want the rows:

> select <- apply(DF1 == "ALL",1,any)
> DF1[select,]

  Acct Tran Group
3 1003  ALL     2
like image 37
R. Schifini Avatar answered Mar 16 '26 20:03

R. Schifini



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!