首页 > 解决方案 > R SAS 到 xlsx 的转换脚本

问题描述

我正在尝试编写一个脚本,该脚本允许我将 SAS 数据集的文件夹快速转换为 .xlsx 并将它们放在不同的文件夹中。这是我当前的代码:

require(haven)
require(openxlsx)

setwd(choose.dir())

lapply(list.files(pattern="*.sas7bdat"), function(x) {
  openxlsx::write.xlsx(haven::read_sas(x), path = paste0(choose.dir(),x,".xlsx"))
})

我不断收到以下错误,我不知道为什么:

 Error in saveWorkbook(wb = wb, file = file, overwrite = overwrite) : 
  argument "file" is missing, with no default 

最终代码(感谢@oliver):

require(haven)
require(openxlsx)

setwd(choose.dir())

lapply(list.files(pattern="*.sas7bdat"), function(x) {
  openxlsx::write.xlsx(haven::read_sas(x), file = paste0(gsub("\\.sas7bdat$", "", basename(x)), ".xlsx"))
})

标签: r

解决方案


问题是write.xlsx没有path参数,而是使用file参数。这也记录在函数中,请参阅help("write.xlsx")

outdir <- choose.dir() #<== choose only directory once
lapply(list.files(pattern="*.sas7bdat"), function(x) {

  # Obtain the basename of the file, without SAS extension
  x_basename <- gsub('\\.sas7bdat$', '', basename(x))

  # Write the file to Excel
  openxlsx::write.xlsx(haven::read_sas(x), 
                       # Use "file" instead of "path"
                       file = paste0(outdir, x_basename, ".xlsx"))
})

推荐阅读