Search code examples
rdataframepipesubsetmagrittr

Subset data frame column using pipe and dot


I want to learn how to properly use the "." when subsetting with magrittr.

Given a dataframe myDataframe,

myDataFrame <- data.frame(c(1,2,3,3,3,4,5), c(10,11,12,13,14,15,16))
#  c.1..2..3..3..3..4..5. c.10..11..12..13..14..15..16.
#1                      1                            10
#2                      2                            11
#3                      3                            12
#4                      3                            13
#5                      3                            14
#6                      4                            15
#7                      5                            16

I want to remove all rows with 3 in the first column, which I could do with myDataFrame[ myDataFrame[,1] != 3 ,] to get this result:

#  c.1..2..3..3..3..4..5. c.10..11..12..13..14..15..16.
#1                      1                            10
#2                      2                            11
#6                      4                            15
#7                      5                            16 

However, I need to do it with a pipe (and I can't name the columns of the dataframe).

When I try to run myDataFrame %>% "[" (.[,1] != 3) I get an "undefined columns selected" error. How do I select one column within a dataframe referred to with a dot?


Solution

  • We can keep it in a {} i.e.

    myDataFrame %>% 
           {.[.[[1]] != 3,]}
    #    c.1..2..3..3..3..4..5. c.10..11..12..13..14..15..16.
    #1                      1                            10
    #2                      2                            11
    #6                      4                            15
    #7                      5                            16
    

    Or in an extended form

    myDataFrame %>% 
              {`[`(.[,1]) != 3} %>%
                            myDataFrame[.,]