I am trying to output a sas7bdat format dataset from R, but it can't be opened, any suggestion to solve the problem? here is a sample code, thank you!
setwd("C:\\...\testfolder")
library(car)
mydata<- mtcars
haven::write_sas(mydata, "mydata.sas7bdat")
According to the help file:
The write_sas()
function has been deprecated.
write_sas()
creates sas7bdat files. Unfortunately the SAS file format is complex and undocumented, so write_sas()
is unreliable and in most cases SAS will not read files that it produces.
write_xpt()
writes files in the open SAS transport format, which has limitations but will be reliably read by SAS.
how to import xpt file into SAS? thank you.
https://communities.sas.com/t5/SAS-Programming/Convert-XPT-to-SAS-Datasets/m-p/97873#M20625
Another option is to use the foreign package which generates a delimited file and the data step syntax for reading in the file. If you're not using tempfiles - the path would make more sense than in this example and would be the actual path in the SAS code.
library(foreign)
datafile <- tempfile()
codefile <- tempfile()
write.foreign(head(iris), datafile, codefile, package="SAS", dataname="iris_ds", validvarname="V7")
#> Some variable names were abbreviated or otherwise altered.
writeLines(readLines(datafile))
#> 5.1,3.5,1.4,0.2,1
#> 4.9,3,1.4,0.2,1
#> 4.7,3.2,1.3,0.2,1
#> 4.6,3.1,1.5,0.2,1
#> 5,3.6,1.4,0.2,1
#> 5.4,3.9,1.7,0.4,1
writeLines(readLines(codefile))
#> * Written by R;
#> * write.foreign(head(iris), datafile, codefile, package = "SAS", ;
#>
#> PROC FORMAT;
#> value Species
#> 1 = "setosa"
#> 2 = "versicolor"
#> 3 = "virginica"
#> ;
#>
#> DATA iris_ds ;
#> INFILE "C:\Users\sazimmer\AppData\Local\Temp\RtmpeAHqom\file5ff446a5df2"
#> DSD
#> LRECL= 21 ;
#> INPUT
#> Sepal_Length
#> Sepal_Width
#> Petal_Length
#> Petal_Width
#> Species
#> ;
#> LABEL Sepal_Length = "Sepal.Length" ;
#> LABEL Sepal_Width = "Sepal.Width" ;
#> LABEL Petal_Length = "Petal.Length" ;
#> LABEL Petal_Width = "Petal.Width" ;
#> FORMAT Species Species. ;
#> RUN;
unlink(datafile)
unlink(codefile)
Created on 2025-01-28 with reprex v2.1.1
Thank you for your response!
Following the link you provided, it works to create a xpt file, but unable to read into SAS, error message says it is not a SAS file.
I tried your sample code, didn't find the generated dataset. Thanks.
For my example, I made temporary files. You should add actual names such as:
datafile <- "iris.dat"
codefile <- "read_iris.sas"
Got it, will try again, thank you!