Export dataframe to SAS file with extension .sas7bdat

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?

Curious, what error are you getting? You're using write_sas and not write_SAS, correct?

1 Like

Yes, write_sas

Sorry for my error.

What error message did you receive?

I've received no error message.

When I tried to open the dataset in SAS it just didn't opened.

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:

  1. 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.
  2. After you write the file with write_sas(), try reading it back into R with read_sas(), if that works then it wrote correctly.
  3. How are you trying to open the file in SAS? Have you tried reading it in with PROC IMPORT?
1 Like

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".

2 Likes

Ah, good to know. It has been a while since I have needed to use SAS, but hadn't had any issues in the past when using haven and SAS Enterprise Guide.

1 Like

@StatSteph

That was the solution I've used but instead of csv, xlsx.

Thank you very much.

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. :frowning:

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)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.