I suspect this is a bug in library(foreign) but I am not sure.
When I export a dataframe containing a boolean vector with write.foreign, the resulting SASDATA file causes an error on SAS import.
Example:
df = data.frame(id = c(1,2,3), boolean = c(TRUE,FALSE,TRUE))
library(foreign)
write.foreign(df, "test.sasdata", "test.sas",
"SAS", dataname="WORK.TEST", validvarname="V7")
Contents of test.sasdata:
1,TRUE
2,FALSE
3,TRUE
Output from SAS when I run “test.sas”:
NOTE: Invalid data for boolean in line 1 3-6
RULE: ----+----1--...
1 1,TRUE 6
id=1 boolean=. _ERROR_=1 _N_=1
... (errors for remaining rows)
The workaround is to do:
df$boolean <- as.numeric(df$boolean)
before export. Or, more generically:
logicals <- sapply(df, is.logical)
if (any(logicals))
df[logicals] <- lapply(df[logicals], as.numeric)
Am I doing something wrong with write.foreign? Or is this a bug?
EDIT: Revised code above to use sapply/lapply as writeForeignSAS does. I have submitted a patch to writeForeignSAS which incorporates the above.
Thanks to DWin for his assistance.
Given that ‘logical’ is not listed among the classes that are claimed to be properly exported to SAS, you could hardly call it a bug.