Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In dplyr, is it possible to specify where to add a new column using mutate?

Tags:

dataframe

r

dplyr

Currently I have to use add_column to directly insert a new column into a desired position, or use mutate, then select with the new desired column order.

mips.group <- str_extract(mips.manifest$PlateName, "[:alnum:]+_([[:alnum:]&&[^P]]+(_CL)?)?|(KORgex)")

mips.manifest %<>%
  add_column(MIPSGroup=mips.group, .after="PlateName")

Is it possible to directly tell mutate where to add the new column, and if not, is there a reason for this?

like image 806
gaelgarcia Avatar asked Apr 24 '18 22:04

gaelgarcia


2 Answers

Looking at the code of mutate, it appears it wouldn't be easy since eventually it dives into a C-function:

> mutate
function (.data, ...) 
{
    UseMethod("mutate")
}
<environment: namespace:dplyr>
> methods(mutate)
[1] mutate.data.frame* mutate.default*    mutate.tbl_df*    
see '?methods' for accessing help and source code
> getAnywhere(mutate.tbl_df)
A single object matching ‘mutate.tbl_df’ was found
It was found in the following places
  registered S3 method for mutate from namespace dplyr
  namespace:dplyr
with value

function (.data, ...) 
{
    dots <- named_quos(...)
    mutate_impl(.data, dots)
}
<environment: namespace:dplyr>
> mutate_impl
Error: object 'mutate_impl' not found
> getAnywhere(mutate_impl)
A single object matching ‘mutate_impl’ was found
It was found in the following places
  namespace:dplyr
with value

function (df, dots) 
{
    .Call(`_dplyr_mutate_impl`, df, dots)
}
<environment: namespace:dplyr>

Seems doubtful that modifications will be welcomed since you already have a workable solution.

like image 166
IRTFM Avatar answered Oct 26 '22 23:10

IRTFM


There is a feature request on the github page of dplyr regarding this question. You can read about this here. But for now it is left as is.

But you can always add your reasons to the discussion.

like image 28
phiver Avatar answered Oct 26 '22 23:10

phiver