Home > Enterprise >  Creating Fixed Width File in R with unique positions for each element
Creating Fixed Width File in R with unique positions for each element

Time:09-23

I have data

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))

I am trying to create a fixed with text file, but I want to have some of the columns up unique amounts of space. So let's say I want the Animal column to be from positions 1-10, but I want Fur to be in 50-54, and then I want Color to be in 100-120. How would I go about doing this in R?

CodePudding user response:

Loop through columns pad each with matching width:

# 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

CodePudding user response:

We could use str_pad to create a fixed length string

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)
   })
  • Related