-
-
Save oousmane/f53c29925eccf37e842776e20a92d3f1 to your computer and use it in GitHub Desktop.
Generate fixed width file in R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#' 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) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment