用变量重命名列名 [英] renaming column names with variable

查看:86
本文介绍了用变量重命名列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用新名称重命名特定列,该新名称是 dplyr 中的变量。

I want to rename a specific column with new name which comes as a variable in dplyr.

newName = paste0('nameY', 2017)

我尝试过的是

iris %>% 
    rename(newName = Petal.Length) %>%
    head(2)

给出

Sepal.Length Sepal.Width newName Petal.Width Species
         5.1         3.5     1.4         0.2  setosa
         4.9         3.0     1.4         0.2  setosa

我正在获取 newName 不是 nameY2017 ,这很正常。所以我尝试了

I am getting newName not nameY2017 which is normal. So I tried

iris %>% 
    rename_(eval(newName) = 'Petal.Length')

但是随后出现错误。


错误: iris%>%named_(eval(newName)=

Error: unexpected '=' in "iris %>% rename_(eval(newName) ="

是否有正确的方法可以使用 dplyr
我知道我可以做类似的事情

Is there a proper way to do it with dplyr? I know I can do something like

names(iris)[3] <- newName

但这不是 dplyr 解决方案。

推荐答案

此帖子中此 dplyr重命名标准评估功能无法按预期运行?

您的代码:

newName = paste0('nameY', 2017)
iris %>% 
  rename(newName = Petal.Length) %>%
  head(2)

解决方案:

iris %>% 
  rename_(.dots = setNames("Petal.Length",newName)) %>%
  head(2)

输出:

  Sepal.Length Sepal.Width nameY2017 Petal.Width Species
1          5.1         3.5       1.4         0.2  setosa
2          4.9         3.0       1.4         0.2  setosa

这篇关于用变量重命名列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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