R/fped_download.R

Defines functions fped_download

Documented in fped_download

#' Download FPED data
#'
#' @return download FPED data
#' @export
#'
fped_download <- function(){
    url <- xml2::read_html('https://www.ars.usda.gov/northeast-area/beltsville-md-bhnrc/beltsville-human-nutrition-research-center/food-surveys-research-group/docs/fped-databases/') |>
        rvest::html_elements(xpath = '//a[@href]') |>
        set::grep_and(c('FPED_','sas.exe','DR')) |>
        do::attr_href() |>
        sprintf(fmt = 'https://www.ars.usda.gov%s')
    fpeddir <- paste0(get_config_path(),'/fped')
    if (!dir.exists(fpeddir)) dir.create(fpeddir,recursive = TRUE)
    url <- c(url,
             'https://www.ars.usda.gov/ARSUserFiles/80400530/foodlink/Mypyr_iff.exe',
             'https://www.ars.usda.gov/ARSUserFiles/80400530/foodlink/Mypyr_tot.exe',
             'https://www.ars.usda.gov/ARSUserFiles/80400530/apps/MPED_2.EXE',
             'https://www.fns.usda.gov/sites/default/files/healthy_eating_index/cnppmyp_v1nhanes0304_wjfrt.sas7bdat',
             'https://www.fns.usda.gov/sites/default/files/healthy_eating_index/cnppmyp_v1NHANES9900_wjfrt-SPSS.zip',
             'https://www.fns.usda.gov/sites/default/files/healthy_eating_index/cnppmypyrequivdb_v1_wjfrt-SPSS.zip')
    for (i in 1:length(url)) {
        fi <- do::file.name(url[i]) |> tolower() |> do::Replace0('.exe','.sas7bdat','.zip')
        ext <- ifelse(fi=='cnppmyp_v1nhanes0304_wjfrt','.sas7bdat','.zip')
        (destfile <- paste0(get_config_path(),'/fped/',fi,ext))
        cat(crayon::red(paste0(i,'/',length(url))),fi,'\n')
        nullcon <- file(nullfile(), open = "wb")
        sink(nullcon, type = "message")
        wait <- TRUE
        while (wait) {
            download <- tryCatch(download.file(url[i],destfile,mode = 'wb'),
                                 error=function(e) 'e',
                                 warning=function(w) 'w')
            wait <- ifelse(download=='e' | download=='w',TRUE,FALSE)
        }
        sink(type = "message")
        close(nullcon)
    }

    # 1999-2000,2001-2002
    'https://www.ars.usda.gov/northeast-area/beltsville-md-bhnrc/beltsville-human-nutrition-research-center/food-surveys-research-group/docs/mypyramid-equivalents-product-downloads/'
    'https://www.ars.usda.gov/ARSUserFiles/80400530/apps/MPED_2.EXE'
    if (do::cnOS()) cat(paste0(tmcn::toUTF8('\n\u5DF2\u6210\u529F\u4E0B\u8F7D'),i,
                               tmcn::toUTF8('\u4E2AFPED\u6587\u4EF6,\u8BF7\u52A0\u538B\u540E\u518D\u4F7F\u7528')))
    if (do::cnOS()) cat(tmcn::toUTF8("\n\n\u4E0B\u8F7D\u5730\u5740:"),fpeddir)
    if (!do::cnOS()) cat(paste0('\nSuccessfully download ',i,' FPED files. Please unzip them before use\n\nPath of FPED:',fpeddir))

}
yikeshu0611/nhanesR documentation built on Jan. 29, 2022, 6:08 a.m.