Michael
Michael

Reputation: 1575

creating a new data frame by subsetting and manipulating an existing data frame in one step using dplyr

So I am trying to learn how to use dplyr and some basic procedures are eluding me.

For example, the following is pretty simple in base, but I don't know how to replicate it in dplyr in a single step.

 my_data <- with(mtcars, data.frame(   cylinders = cyl[cyl == 6], 
                                       twice_weight = wt[cyl == 6]*2))

I could create the variable twice_weight with mutate() and then subset the result with select(), but that seems cumbersome.

Thank you!

Upvotes: 1

Views: 1073

Answers (2)

talat
talat

Reputation: 70266

Could also do:

filter(mtcars, cyl == 6) %>%
  transmute(cylinders = cyl, twice_weight = wt*2)

#  cylinders twice_weight
#1         6         5.24
#2         6         5.75
#3         6         6.43
#4         6         6.92
#5         6         6.88
#6         6         6.88
#7         6         5.54

.. transmute drops all columns except for those that are explicitly called inside it and grouping variables.

Upvotes: 4

akrun
akrun

Reputation: 887068

Try

library(dplyr)
mtcars %>% 
      filter(cyl==6) %>% 
      mutate(twice_weight=wt*2) %>% 
      select(cylinders=cyl, twice_weight)
#   cylinders twice_weight
#1         6         5.24
#2         6         5.75
#3         6         6.43
#4         6         6.92
#5         6         6.88
#6         6         6.88
#7         6         5.54

Upvotes: 2

Related Questions