在 R 中为每个元素创建具有唯一位置的固定宽度文件
Creating Fixed Width File in R with unique positions for each element
我有资料
structure(list(Animal = c("dog", "cat", "dog ", "cat"), Fur = c("no",
"no", "yes", "yes"), Color = c("Pearl", "Midnight ", "Midnight ",
"Pearl")), class = "data.frame", row.names = c(NA, -4L))
我正在尝试创建一个固定的文本文件,但我希望某些列的数量达到 space 的唯一数量。假设我希望 Animal
列位于位置 1-10,但我希望 Fur
位于 50-54,然后我希望 Color
位于 100-120 .我将如何在 R 中执行此操作?
我们可以使用str_pad
来创建固定长度的字符串
library(stringr)
library(purrr)
library(tibble)
library(dplyr)
out <- df1 %>%
mutate(across(everything(), trimws)) %>%
add_row(!!! setNames(names(df1), names(df1)), .before = 1) %>%
pmap_chr( ~ {
cn1 <- str_pad(..1, width = 10, pad = " ", side = "left")
blnk <- strrep(" ", 39)
cn2 <- str_pad(..2, width = 5, pad = " ", side = "left")
blnk2 <- strrep(' ', 45)
cn3 <- str_pad(..3, width = 21, pad = " ", side = "left")
str_c(cn1, blnk, cn2, blnk2, cn3)
})
循环遍历具有匹配宽度的列填充:
# set widths
w <- c(10, diff(c(10, 54, 120)))
# pad every column with matching width
x <- do.call(paste0, lapply(seq(w), function(i){ formatC(trimws(df[, i ]), width = w[ i ]) }))
# output
write(x, file = "tmp.txt")
tmp.txt
dog no Pearl
cat no Midnight
dog yes Midnight
cat yes Pearl
我有资料
structure(list(Animal = c("dog", "cat", "dog ", "cat"), Fur = c("no",
"no", "yes", "yes"), Color = c("Pearl", "Midnight ", "Midnight ",
"Pearl")), class = "data.frame", row.names = c(NA, -4L))
我正在尝试创建一个固定的文本文件,但我希望某些列的数量达到 space 的唯一数量。假设我希望 Animal
列位于位置 1-10,但我希望 Fur
位于 50-54,然后我希望 Color
位于 100-120 .我将如何在 R 中执行此操作?
我们可以使用str_pad
来创建固定长度的字符串
library(stringr)
library(purrr)
library(tibble)
library(dplyr)
out <- df1 %>%
mutate(across(everything(), trimws)) %>%
add_row(!!! setNames(names(df1), names(df1)), .before = 1) %>%
pmap_chr( ~ {
cn1 <- str_pad(..1, width = 10, pad = " ", side = "left")
blnk <- strrep(" ", 39)
cn2 <- str_pad(..2, width = 5, pad = " ", side = "left")
blnk2 <- strrep(' ', 45)
cn3 <- str_pad(..3, width = 21, pad = " ", side = "left")
str_c(cn1, blnk, cn2, blnk2, cn3)
})
循环遍历具有匹配宽度的列填充:
# set widths
w <- c(10, diff(c(10, 54, 120)))
# pad every column with matching width
x <- do.call(paste0, lapply(seq(w), function(i){ formatC(trimws(df[, i ]), width = w[ i ]) }))
# output
write(x, file = "tmp.txt")
tmp.txt
dog no Pearl
cat no Midnight
dog yes Midnight
cat yes Pearl