Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr not accepting paste0() as old_name in rename()

Tags:

r

dplyr

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.

like image 962
MorrisseyJ Avatar asked Sep 05 '25 23:09

MorrisseyJ


1 Answers

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
like image 69
akrun Avatar answered Sep 11 '25 04:09

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!