Home > Mobile >  select and mutate using native pipe
select and mutate using native pipe

Time:05-04

I'm rewriting a package to move from using magrittr pipe to native pipe (for fun) and already finding some troubles with regards to placeholders. My original codes is something like this:

new_df<- original_df %>%
select(ncol(original_df)-1,ncol(original_df)) %>% #select the utimate and penultimate column
mutate(new =.[[1]]/.[[2]]*100) #divide one column by another to create a new column. 

With the new pipe, I have not yet figured out how to deal with .[[]] and mutate.

new_df<-original_df|>
select(ncol(original_df)-1,ncol(original_df))|> 
mutate(new =.[[1]]/.[[2]]*100)

I've tried mutate (mutate((.) new =.[1]/.[2]*100) with no luck (among many other things!)

Thanks!

CodePudding user response:

Change your mutate code to something like

mtcars |>
  select(ncol(mtcars)-1, ncol(mtcars)) |>
  mutate(new = cur_data()[[1]]/cur_data()[[2]]*100)

This will be safer because curr_data will with with group_by where as the old method of .[[1]] would not. You can use this more robust selection with either pipe.

  •  Tags:  
  • r
  • Related