rfileflat-file

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


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?


Solution

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