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().


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
           con = a_file)

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

#notice that base::read.csv changes spaces to dots

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

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.