2

I am attempting to download some files onto my local from an ftp-server. I have had success using the following method to move .txt and .csv files from the server but not the .sas7bdat files that I need.

protocol <- "sftp"
server <- "ServerName"
userpwd <- "User:Pass"
tsfrFilename <- "/filepath/file.sas7bdat" 
ouptFilename <- "out.sas7bdat"

# Run #
## Download Data
url <- paste0(protocol, "://", server, tsfrFilename)
data <- getURL(url = url, userpwd=userpwd)

## Create File
fconn <- file(ouptFilename)
writeLines(data, fconn)
close(fconn)

When I run the getURL command, however, I am met with the following error:

Error in curlPerform(curl = curl, .opts = opts, .encoding = .encoding) : 
  embedded nul in string:

Does anyone know of any alternative way which I can download a sas7bdat file from an ftp-server to my local, or if there is a way to alter my code below to successfully download the file. Thanks!

Joe
  • 62,789
  • 6
  • 49
  • 67
Justin Klevs
  • 651
  • 6
  • 17
  • 2
    Try `getBinaryURL()` instead. That's safer with binary data. – MrFlick May 08 '17 at 21:00
  • `download.file()`? – Parfait May 09 '17 at 03:02
  • @MrFlick I was able to use the function you mentioned to get past that particular step. However the writeLines function gives me the error message "invalid 'text' argument" – Justin Klevs May 09 '17 at 13:29
  • Use `writeBin()` rather than `writeLines()` like in [this question](http://stackoverflow.com/questions/14426359/downloading-large-files-with-r-rcurl-efficiently). sas7bdat files are binary, not text. They don't have "lines". – MrFlick May 09 '17 at 13:41
  • 1
    @MrFlick of course. Unfortunately I am getting an error here too, "WriteBin() can only write to a binary connection", otherwise my code is set up the same as I have it above – Justin Klevs May 09 '17 at 13:47

1 Answers1

6

As @MrFlick suggested, I solved this problem using getBinaryURL instead of getURL(). Also, I had to use the function write() instead of writeLines(). The result is as follows:

protocol <- "sftp"
server <- "ServerName"
userpwd <- "User:Pass"
tsfrFilename <- "/filepath/file.sas7bdat" 
ouptFilename <- "out.sas7bdat"

# Run #
## Download Data
url <- paste0(protocol, "://", server, tsfrFilename)
data <- getBinaryURL(url = url, userpwd=userpwd)

## Create File
fconn <- file(ouptFilename)
write(data, fconn)
close(fconn)

Alternatively, to transform the read data into R data frame, one can use the library haven, as follows

library(haven)
df_data=  read_sas(data)
cdutra
  • 587
  • 6
  • 15