Search code examples
rdownloadnetcdf

Downloading NetCDF files with R: Manually works but the downloaded file is smaller


I am trying to download NetCDF files from: https://ftp.cpc.ncep.noaa.gov/NMME/prob/netcdf/

When I manually download the files I got a file of about 5000 Kb, when it is downloaded with the code below I got a file of 119 Kb and it is not usable.

now <- as.Date(Sys.Date())
now <- paste0(substr(now,1,4),substr(now,6,7))
filename <- paste0('prate.',now,'.prob.adj.seas',".nc")
root <- 'https://ftp.cpc.ncep.noaa.gov/NMME/prob/netcdf/'
download.file(root, filename,mode = "wb")

Any suggestion? Thanks


Solution

  • You use the arguments of download.file() incorrectly. Try

    ## your code
    now <- as.Date(Sys.Date())
    now <- paste0(substr(now,1,4),substr(now,6,7))
    filename <- paste0('prate.',now,'.prob.adj.seas',".nc")
    root <- 'https://ftp.cpc.ncep.noaa.gov/NMME/prob/netcdf/' # main_url
    
    ## changes
    path <- getwd() # example of donwload directory
    download.file(url = paste0(root, filename), 
                  destfile = file.path(path, basename(filename)))
    

    See ?download.file

    1. The first argument to download.file() is a url, i.e., "https://ftp.cpc.ncep.noaa.gov/NMME/prob/netcdf/prate.202311.prob.adj.seas.nc".
    2. Then specify destfile, i.e., the local path, a combination of download directory and file name. On Mac OS X it looks like "/Users/YourUsername/Desktop/prate.202311.prob.adj.seas.nc".
    download.file(url = paste0(root, filename), 
                  destfile = file.path(path, basename(filename)))
    

    equals

    download.file(
      url = "https://ftp.cpc.ncep.noaa.gov/NMME/prob/netcdf/prate.202311.prob.adj.seas.nc",
      destfile = "/Users/YourUsername/Desktop/prate.202311.prob.adj.seas.nc")
    

    I think mode = "wb" is not necessary. Haven't checked.