Paul
Paul

Reputation: 117

Multiple manipulations to the same variable using dplyr

How can make I several, sequential manipulations of the same variable using dplyr, but more elegantly than the code below?

Specifically, I would like to remove the multiple calls to car_names = without having to nest any of the functions.

     mtcars2 <- mtcars %>% mutate(car_names = row.names(.)) %>% 
        mutate(car_names=stri_extract_first_words(car_names)) %>% 
mutate(car_names=as.factor(car_names)

Upvotes: 2

Views: 1135

Answers (1)

FlorianGD
FlorianGD

Reputation: 2436

If you want to type less and not nest the function, you can use the pipe inside the mutate call :

library(dplyr)
library(stringi)

# What you did
mtcars2 <- mtcars %>% 
  mutate(car_names = row.names(.)) %>% 
  mutate(car_names = stri_extract_first_words(car_names)) %>% 
  mutate(car_names = as.factor(car_names))

# Another way with less typing and no nesting       
mtcars3 <- mtcars %>% 
  mutate(car_names = rownames(.) %>% 
           stri_extract_first_words(.) %>% 
           as.factor(.))

identical(mtcars2, mtcars3)
[1] TRUE

Upvotes: 1

Related Questions