How to rename a column to a variable name “in a tidyverse way”

匿名 (未验证) 提交于 2019-12-03 02:30:02

问题:

I've created a simple data frame (dput below):

    date      ticker     value ------------------------------   2016-06-30  A2M.ASX   0.0686   2016-07-29  A2M.ASX  -0.0134   2016-08-31  A2M.ASX  -0.0650   2016-09-30  A2M.ASX   0.0145   2016-10-31  A2M.ASX   0.3600   2016-11-30  A2M.ASX  -0.1429 

I want to change the value column's name to whatever is in my metric variable name, and I want to do it in a dplyr way.

My sample data:

df = structure(list(date = c("2016-06-30", "2016-07-29", "2016-08-31", "2016-09-30", "2016-10-31", "2016-11-30"), ticker = c("A2M.ASX", "A2M.ASX", "A2M.ASX", "A2M.ASX", "A2M.ASX", "A2M.ASX"), value = c(0.0686, -0.0134, -0.065, 0.0145, 0.36, -0.1429)), .Names = c("date", "ticker", "value"), row.names = c(NA, 6L), class = "data.frame") metric = "next_return" 

I know how to do it in one line:

colnames(df)[3] = metric 

But I want do it in a tidyverse way so I can use it in a pipe. I've been tinkering with replace_ but I only manage to get errors:

> dplyr::rename_(df, "ticker" = metric) Error: `next_ret_1M` contains unknown variables 

回答1:

With the newest dplyr (>0.7.0) you would use

rename(df, !!metric:=value) 

The syntax is "new_name=old_name" and you need to use := with !! to put a variable on the left side of a parameter name.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!