2

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?

2
  • those should be blank Commented Sep 22, 2021 at 19:19
  • Why do you have trailing spaces in one of the "dog " and "Midnight " ? Commented Sep 22, 2021 at 19:56

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

4 Comments

how do you save the file to be a fixed text file afterwards where all the columns have a specific position?
@rj44 you may use write to a .txt file
and if I use side=right then all of the data should be at the start of the position required then yes?
@rj44 yes, that is correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.