3

I am trying to build a function that imports a bunch of csv files and cleans them. One of the cleaning functions involves pulling the year from the csv file name and pasting it to a column name, using dplyr rename(). For some reason it won't work. I am trying to work out why.

Here is a quick example:

df <- data.frame('value' = 1:5)
df
  value
1     1
2     2
3     3
4     4
5     5

When I try and rename, however:

rename(df, paste0('value', '_', gsub('([a-z]+_)|(\\.csv)', '', 'csv_2018.csv')) = 'value')

Throws:

Error: unexpected '=' in "rename(df, paste0('value', '_', gsub('([a-z]+_)|(\\.csv)', '', 'csv_2018.csv')) ="

Notably this works fine:

paste0('value', '_', gsub('([a-z]+_)|(\\.csv)', '', 'csv_2018.csv'))
[1] "value_2018"

Also this works fine:

rename(df, 'value_2018' = 'value')
  value_2018
1          1
2          2
3          3
4          4
5          5

Problem seems to be with paste0() (rather than gsub() ) as this also does not work:

rename(df, paste0('value', '_') = 'value')

Throwing the same error:

Error: unexpected '=' in "rename(df, paste0('value', '_') ="

Obviously:paste0('value', '_') works to give: "value_"

I can solve this in other ways, but was wondering why dplyr would not accept paste0 as an input for new_name.

1 Answer 1

4

Expressions on the lhs of = will not work. Instead use := with !!

library(dplyr)
rename(df, !! paste0('value', '_', gsub('([a-z]+_)|(\\.csv)', '',
          'csv_2018.csv')) := 'value')
  value_2018
1          1
2          2
3          3
4          4
5          5

Or another option is rename_with

rename_with(df, ~ paste0('value', '_', gsub('([a-z]+_)|(\\.csv)', '',
           'csv_2018.csv')), 'value')
  value_2018
1          1
2          2
3          3
4          4
5          5

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.