dplyr:在mutate_at函数中访问列名 [英] dplyr: access column name in mutate_at function

查看:57
本文介绍了dplyr:在mutate_at函数中访问列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过在data.frame中减去名称几乎相同的另一列来更正该列,但是该另一列具有后缀.我想为此使用 mutate_at 函数.

I would like to correct a column in a data.frame by subtracting from it another column with nearly identical name, but this other column has a suffix. I would like to use the mutate_at function for this.

试图弄清楚这一点,我一直努力访问mutate_at函数部分中的列名,以使用它来访问其他列.

Trying to figure this out, I have struggled to access the name of a column in the function part of mutate_at, to the use it to access the other column.

我在下面的一个小示例中对此进行了显示,但是基本上我想访问在时使用的列的名称.,然后从管道中的数据中选择一个包含与.相同的名称,但带有后缀(在其后为"_ new" ).

I show this in a small example below, but basically I would like to access the name of the column used at the moment . and then select from the data in the pipe a column that has the same name as . but with a suffix (below that would be "_new").

感谢您的帮助!

这里是我希望如何执行此操作的示例-但这不起作用.

Here is an example of how I would have liked to do it - but this does not work.

library(tidyverse)
data("mtcars")
new <- mtcars/4
names(new) <-paste0(names(new),"_new")

df <- bind_cols(mtcars,new)

df %>% 
  mutate_at(.vars = vars(carb,disp),
            .funs = list(corrected = ~ . - df %>% pull(paste0(names(.),"_new"))))

df %>% pull(paste0("carb","_new"))

推荐答案

为什么不使用 mutate_at 而不结合使用 mutate cross cur_column 即:

Instead of using mutate_at why not use mutate combined with across and cur_column i.e:

df %>% 
  mutate( across( c(carb,disp), ~ . - pull(df, paste0(cur_column(), "_new") ),  .names = "{.col}_corrected") )

这篇关于dplyr:在mutate_at函数中访问列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆