在dplyr的重命名函数中输入新列名作为字符串

时间:2022-03-24 10:36:13

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.

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

For example say I had this function

比如说我有这个功能

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

If I run this

如果我运行这个

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

I get

我明白了

  a new
1 1   4
2 2   5
3 3   6

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

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

  a x_1
1 1   4
2 2   5
3 3   6

Is there anyway of doing this?

无论如何这样做?

1 个解决方案

#1


21  

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:

我想这就是你要找的东西。正如@Henrik建议的那样使用rename_,但是参数有一个,比方说,有趣的,名字:

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

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

请注意使用setNames在列表中使用new的值作为名称。

#1


21  

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:

我想这就是你要找的东西。正如@Henrik建议的那样使用rename_,但是参数有一个,比方说,有趣的,名字:

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

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

请注意使用setNames在列表中使用new的值作为名称。