r - 如何写一个固定宽度的文件?
问题描述
我应该根据固定宽度的列编写一个具有特定格式的 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))
解决方案
这是使用格洛腾迪克答案的更自动化的版本
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)
}
推荐阅读
- r - 在 R 中生成卡方分布的随机数
- java - 在 Android 中使用 Dlib、JNI 进行人脸识别的问题
- php - 为什么在加载 pdo 时会出现“在 null 上调用成员函数 prepare()”?
- python - 根据 Pandas 中另一列中的值范围聚合一列的内容
- python - 字典错误发生异常:在封闭范围内赋值之前引用了 NameError 自由变量
- postgresql - Payara/Glassfish 上的 Postgres 连接池问题
- logging - Keycloak记录到logstash
- android - 在 Android 上访问当前用户 ID
- javascript - 如何使用返回 Promises 的 NAPI 创建异步函数
- php - Windows 上的 Zend_config.h