How to replace colnames with vector values - using

2019-09-02 19:03发布

问题:

This question already has an answer here:

  • How do I add a prefix to several variable names using dplyr? 3 answers

I'm trying to use dplyr as much as I can in my operations. Now I have a simple vector containing the string elements I would like to replace in the colnames() of my data.table.

I read some posts and tried, but can't get my head around how it should look like.

My code

> head(tickerData)
           AAK.ST.Open AAK.ST.High AAK.ST.Low AAK.ST.Close AAK.ST.Volume AAK.ST.Adjusted
2007-01-02       199.5       199.5      195.0        198.0         74400          159.54
2007-01-03       198.0       202.5      196.5        202.5         79100          163.17
2007-01-04       201.0       206.0      200.0        204.0        258500          164.38
2007-01-05       204.0       207.0      204.0        205.5         42100          165.59
2007-01-08       205.0       205.0      201.5        205.0        155300          165.18
2007-01-09       203.0       205.0      202.0        204.0        149000          164.38

> colName <- c('Open', 'High', 'Low', 'Close', 'Volume', 'Adj.Close')

> tickerData <- tickerData %>% ggplot2::fortify() %>%
+     # rename
+     rename(.dots = setNames(colName, 'new'))
Error: Arguments to rename must be unquoted variable names. Arguments .dots are not.

How should the syntax look like in this case?

回答1:

what about

library(dplyr)

tickerData %>%
  setNames(colName)


标签: r dplyr