R reading Excel files with carriage return
I am creating a subroutine in R to import multiple Excel files that I need to combine into one large txt file. I am using read.xls function. Some of these xls files return carriage returns ("\ n"). Then when I write txt files (write.table) R interprets this "\ n" as newlines. How can I clear the xls files or read them correctly to remove unnecessary "\ n"?
Thank!
source to share
The columns in the table are almost certainly factors (the default for character columns in R). So we can just change the factors in each column.
Some bogus data first
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 loop for
to iterate over the column names:
for(i in 1:ncol(dd))
levels(dd[,i]) = gsub("\n","", levels(dd[,i]))
If you want to remove the loop for
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])))
source to share