首页 > 解决方案 > 如何写一个固定宽度的文件?

问题描述

我应该根据固定宽度的列编写一个具有特定格式的 txt 文件(例如,第 1-8 列中的第一个变量,第 9-15 列中的第 2 个变量...)。

原始数据的长度不同,它们必须放在指定列的右侧。例如:值“-15.96”和“12.489”必须写在第一行和第二行的1-8列,而“-872.6”和“1723.6”必须写在9-15列。这将是:

123456789012345 (n columns)
  -15.96 -872.6
  12.489 1723.6

我怎么能用 R 做到这一点?现在我有一个像这样的简单表:

x <- data.frame(a= sample(-500.5:500.8,4),
                b= sample(-250.6:420.9,4))

标签: rfixed-width

解决方案


这是使用格洛腾迪克答案的更自动化的版本

https://gist.github.com/haozhu233/28d1309b58431f4929f78243054f1f58

#' Generate fixed width file in R
#' @description This simple function creates fixed width file with no 
#' extra dependencies. 
#' @param justify "l", "r" or something like "lrl" for left, right, left. 
#' @examples dt <- data.frame(a = 1:3, b = NA, c = c('a', 'b', 'c'))
#' write_fwf(dt, "test.txt", width = c(4, 4, 3))
#' @export
write_fwf = function(dt, file, width, 
                     justify = "l", replace_na = "NA") {
  fct_col = which(sapply(dt, is.factor))
  if (length(fct_col) > 0) {
    for (i in fct_col) {
      dt[,i] <- as.character(dt[,i])
    }
  }
  dt[is.na(dt)] = replace_na
  n_col = ncol(dt)
  justify = unlist(strsplit(justify, ""))
  justify = as.character(factor(justify, c("l", "r"), c("-", "")))
  if (n_col != 1) {
    if (length(width) == 1) width = rep(width, n_col)
    if (length(justify) == 1) justify = rep(justify, n_col)
  }
  sptf_fmt = paste0(
    paste0("%", justify, width, "s"), collapse = ""
  )
  tbl_content = do.call(sprintf, c(fmt = sptf_fmt, dt))
  tbl_header = do.call(sprintf, c(list(sptf_fmt), names(dt)))
  out = c(tbl_header, tbl_content)
  writeLines(out, file)
}

推荐阅读