I'm trying to export a R dataframe to a SAS file with extension .sas7bdat
Using write_sas() from haven package I get an error.
Is there any alternative solution?
Well, you can alternatively use the
foreign
package, though I have never had an issue writing a sas7bdat file with haven. Few things to check:
Make sure you have valid column names for SAS data sets (e.g., no periods
"."
in the column names).
Here
is a list of the rules regarding names.
After you write the file with
write_sas()
, try reading it back into R with
read_sas()
, if that works then it wrote correctly.
How are you trying to open the file in SAS? Have you tried reading it in with
PROC IMPORT
?
FWIW, I'm an R user and SAS user and I've given up on the
write_sas
in haven a long time ago.
read_sas
works but I just write to csv if I need to use something in SAS from R. Something as simple as this doesn't open in SAS and they are all valid variable names:
library(haven)
library(tidyverse)
mtcars %>% as_tibble(rownames = "car") %>%
write_sas("mtcars.sas7bdat")
Created on 2021-11-29 by the reprex package (v2.0.1)
SAS Universal Viewer gives an error that "Unable to load table mtcars. One common cause is when the table has an associated index which was not found".
Makes me wonder if the rownames on the tibble is throwing it off perhaps ?
library(haven)
library(tidyverse)
mtcars %>% as_tibble(rownames = "car") %>%`row.names<-`(NULL) %>%
write_sas("mtcars.sas7bdat")
I don't have SAS on my current system to try unfortunately. 
That wouldn't change anything since tibbles don't have row.names (see below). It seems they will be removing this function from the package.
library(tidyverse)
#> Warning: package 'tibble' was built under R version 4.1.2
#> Warning: package 'readr' was built under R version 4.1.2
d1 <- mtcars %>% as_tibble(rownames = "car")
d2 <- d1 %>%`row.names<-`(NULL)
identical(d1, d2)
#> [1] TRUE
Created on 2021-11-30 by the reprex package (v2.0.1)