wtrs
wtrs

Reputation: 329

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?

Upvotes: 2

Views: 5345

Answers (3)

moodymudskipper
moodymudskipper

Reputation: 47300

If you give only one argument to [.data.frame, it will be used to subset columns.

You can add only one character and make your form work:

myDataFrame %>% "[" (.[,1] != 3,)

Upvotes: 1

Paul Campbell
Paul Campbell

Reputation: 876

dplyr method:

myDataFrame %>% 
  filter_at(vars(1), any_vars(. != 3))

Upvotes: 2

akrun
akrun

Reputation: 887048

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[.,]

Upvotes: 1

Related Questions