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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With