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

查看:110
本文介绍了在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

而我想要新列是我构造的字符串的名称('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

有没有这样做?

推荐答案

我认为这是你正在寻找的。这是@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 来使用新值作为列表中的名称。

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

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

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