R not reading column spaces from csv files

Hello guys. I am trying to import csv files and read few columns from csv to perform data manipulaiton but R seems not recognising coulmn names because csv file has column name with spaces. If i put single character in column name of csv file then there is no problem for R in reading this.

files = list.files()
combinecsv = data.frame(check.names=TRUE)
for (i in 1:length(files)){
print(paste0("combining ", files[i]))
csv = read.csv(file = files[i])
combinecsv= rbind(combinecsv,csv)
}

#this is where the problem is occuring
after sum function, the R is not recognising column names from csv files.

combinecsv = combinecsv %>%
mutate( Col1 = sum (Column 1 name with spaces, na.rm = T),
Col2 = sum(Column 2 name with spaces, na.rm = T),
Col3 = sum(Column 3 name with spaces, na.rm = T),
Col4 = sum( Column 4 name with spaces , na.rm = T) )

Hi tailchopper,

You can try using a single back-quotes(`) around the column names and it will work.

You can also use doBy::renameCol().

#V1

combinecsv = combinecsv %>%
				mutate( Col1 = sum (`Column 1 name with spaces`, na.rm = T),
						Col2 = sum (`Column 2 name with spaces`, na.rm = T),
						Col3 = sum (`Column 3 name with spaces`, na.rm = T),
						Col4 = sum (`Column 4 name with spaces`, na.rm = T))

#V2 Rename the columns to remove the spaces

combinecsv = combinecsv %>%
				doBy::renameCol(names(combinecsv), stringr::str_replace(names(combinecsv)), " ", "_")

# And proceed as you would normal

both options are not working :frowning: actually R is giving an error either object not found or unexpected Token


### write a csv file with column names with spaces to serve as an example

(a_file <- tempfile())
writeLines(text = "col 1,col 2
           1,2
           3,4",
           con = a_file)

# read it
(gotit <- read.csv(a_file))

#notice that base::read.csv changes spaces to dots
names(gotit)

library(dplyr)
gotit %>% 
  mutate(s1 = sum(col.1),
         s2 = sum(col.2))