Skip to content
Prev 25589 / 398502 Next

read.table, write.table, logicals and spaces?

I have some data frames that contain logical values.  When I
write the frame to a file with write.table(df, filename,
row.names=F, sep=','), I end up with the logicals looking like
either ...,FALSE,... or ..., TRUE,... .  That space in front of
the TRUE is causing me problems when I read the frame again with
df <- read.table(filename,header=T,sep=',').  

Reading the data leaves me with this:
[1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
[13]  TRUE FALSE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE
[25]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE
Levels:   TRUE FALSE
[1]    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA    NA
[13]    NA FALSE FALSE    NA    NA    NA FALSE    NA    NA    NA    NA    NA
[25]    NA    NA    NA    NA    NA    NA
[1] " TRUE" " TRUE" " TRUE" " TRUE" " TRUE" " TRUE" " TRUE" " TRUE" " TRUE"
[10] " TRUE" " TRUE" " TRUE" " TRUE" "FALSE" "FALSE" " TRUE" " TRUE" " TRUE"
[19] "FALSE" " TRUE" " TRUE" " TRUE" " TRUE" " TRUE" " TRUE" " TRUE" " TRUE"
[28] " TRUE" " TRUE" " TRUE"

Can anyone suggest a way to read this column so that I can use it
as a logical without having to first do something like

df$valid <- as.logical(sub(' ','',as.character(df$valid)))

Mike