在 dplyr 的重命名函数中输入新列名作为字符串 [英] Enter new column names as string in dplyr's rename function

查看:25
本文介绍了在 dplyr 的重命名函数中输入新列名作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dplyr 的重命名函数要求将新列名作为不带引号的变量名传入.但是我有一个函数,其中列名是通过将字符串粘贴到传入的参数上来构造的,因此是字符串.

dplyr's rename functions require the new column name to be passed in as unquoted variable names. However I have a function where the column name is constructed by pasting a string onto an argument passed in and so is a character string.

例如说我有这个功能

myFunc <- function(df, col){
  new <- paste0(col, '_1')
  out <- dplyr::rename(df, new = old)
  return(out)
}

如果我运行这个

df <- data.frame(a = 1:3, old = 4:6)
myFunc(df, 'x')

我明白了

  a new
1 1   4
2 2   5
3 3   6

而我希望 'new' 列是我构造的字符串的名称 ('x_1'),即

Whereas I want the 'new' column to be the name of the string I constructed ('x_1'), i.e.

  a x_1
1 1   4
2 2   5
3 3   6

无论如何都要这样做吗?

Is there anyway of doing this?

推荐答案

我想这就是您要找的.正如@Henrik 建议的那样,使用 rename_ ,但该参数有一个有趣的名称:

I think this is what you were looking for. It is the use of rename_ as @Henrik suggested, but the argument has an, lets say, interesting, name:

> myFunc <- function(df, col){
+   new <- paste0(col, '_1')
+   out <- dplyr::rename_(df, .dots=setNames(list(col), new))
+   return(out)
+ }
> myFunc(data.frame(x=c(1,2,3)), "x")
  x_1
1   1
2   2
3   3
>

注意使用 setNames 将 new 的值用作列表中的名称.

Note the use of setNames to use the value of new as name in the list.

这篇关于在 dplyr 的重命名函数中输入新列名作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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