0

I am working on automating some spreadsheet work i do, and when using group_by and summarize from dplyr the output doesn't work if the column name has a space in it. I was able to correct after doing a general rename (which i have below).

Is there a more automated way rename column names that have a space in them?

names(dataframe)[3] <- paste("Amount")
Paolo Mossini
  • 1,064
  • 2
  • 15
  • 23
CDHBB
  • 3
  • 2
  • 1
    Use backticks : `\`column name\``. See https://stackoverflow.com/questions/22842232/dplyr-select-column-names-containing-white-space/22842390 – Ronak Shah Oct 08 '20 at 14:17

2 Answers2

2

You can use the dplyr function rename_with() to rename all columns that match a certain condition (in this case that it contains a space). In this example I replace the space in the column name with an underscore:

library(dplyr)

df <- data.frame(a = 1:2,
                 b = LETTERS[1:2],
                 c = 101:102)
names(df) <- c("a", "b b", "c e f")

df %>% 
  rename_with(~ gsub(" ","_", .x), contains(" "))
pieterbons
  • 1,604
  • 1
  • 11
  • 14
  • Thank you, great example..helped me understand. I used a direct assignment (not piping) back to the original DF and it worked. – CDHBB Oct 08 '20 at 19:28
0

make.names() changes every irregular character to a period.

Ron
  • 1