Q:

R reading Excel files with carriage returns

I create a routine in R to import multiple Excel files that I need to merge in one big txt file. I use the read.xls function. Some of these xls files have carriage returns in cells ("\n"). Then, when I write the txt files (write.table) R interpret this "\n" as new lines.
How can I clean the xls files or read properly them to remove the not necessary "\n"?
Thanks!

A:

The columns in your table are almost certainly factors (that's the default for character columns in R). So, we can just change the factors in each column.
First some dummy data
R> dd = data.frame(d1 = c("1", "2\n", "33"), 
                d2 = c("1\n", "2\n", "33"))

##Default, factor
R> levels(dd[,1])
[1] "1"   "2\n" "33"

Next, we use a for loop to go over the column names:
for(i in 1:ncol(dd)) 
  levels(dd[,i]) = gsub("\n","", levels(dd[,i]))

If you want to remove the for loop and use sapply, then this should work
##Can this be improved?
sapply(1:ncol(dd), 
        function(i) levels(dd[,i]) <<- gsub("\n","", levels(dd[,i])))

