首页 > 解决方案 > 在 dplyr 中,是否可以使用 mutate 指定在何处添加新列?

问题描述

目前我必须使用add_column直接将新列插入所需位置,或使用mutate, 然后select使用新的所需列顺序。

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

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

是否可以直接告诉mutate在哪里添加新列,如果没有,是否有这样做的原因?

标签: rdataframedplyr

解决方案


查看 mutate 的代码,它似乎并不容易,因为它最终会潜入 C 函数:

> 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>

似乎怀疑修改是否会受到欢迎,因为您已经有了一个可行的解决方案。


推荐阅读