0

I have a named logical, and I want to use it to filter the original data frame where the logical vector is FALSE

I have tried using the conjunction of the two but this doesn't work.

The named logical vector is as below:

     fr_Ar_COO             fr_C_S              fr_SH        fr_aldehyde 
          TRUE               TRUE               TRUE              FALSE 

And I want to filter a data frame which is like this: (the column names)

fr_Ar_COO             fr_C_S              fr_SH        fr_aldehyde         active 

so fr_aldehyde should be filtered out because the logical vector has it equal to FALSE

0

1 Answer 1

3

Here is one way:

# assuming your data frame is called df,
# and assuming 'v' is the logical vector
df[, names(v)[v]]

Using names(v)[v] will return only the column names for which the logical vector has a TRUE value.

Here is a sample script:

df <- data.frame(A=c(1:3), B=c(4:6), C=c(7:9))
df
v <- c(A=TRUE, B=FALSE, C=TRUE)
df[, names(v)[v]]

  A B C
1 1 4 7
2 2 5 8
3 3 6 9

  A C
1 1 7
2 2 8
3 3 9
4
  • What does v mean in this solution?
    – NelsonGon
    Commented Dec 26, 2018 at 14:12
  • 1
    @NelsonGon Seeing is believing. Check the example I gave. Commented Dec 26, 2018 at 14:13
  • @RonakShah Actually, you're assuming that the order of the named logical vector coincides exactly with the names of the data frame, which may not be the case, see here. Commented Dec 26, 2018 at 15:25
  • @TimBiegeleisen yes, you are right! My bad. Thanks :)
    – Ronak Shah
    Commented Dec 26, 2018 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.