ZT_Geo
ZT_Geo

Reputation: 413

Exporting R data frame to a text file while defining the number of characters allowed in each column and spacing

I have the following data frame.

c1 <- c("Stop", "Go", "Stop", "Go", "Go")
c2 <- c(300,6,800000,20,7000)
df <- data.frame(c1, c2)

I have been trying to use write.table() to export this data frame as a text file as follows.

write.table(df, file = "test", 
            quote = FALSE, 
            col.names = FALSE,
            row.names = FALSE)

I want to define how many characters there are present in every element of each column so that I get the following output in the text file.

#Stop    300
#Go        6
#Stop 800000
#Go       20
#Go     7000

Where in column 1 every value has 4 characters and in column 2 every element has 6 characters and they are separated by one space. For example the value 6 in the data frame would be a character string with 5 spaces before the 6. In column 1 the characters are left justified with spaces after and in column 2 the spaces are before. How can I do this and what functions may be useful?

Upvotes: 1

Views: 109

Answers (2)

lroha
lroha

Reputation: 34556

format() your data using the width argument. This will left pad numeric and right pad character vectors by default. Here the width is set to the maximum number of characters per column.

write.table(
  lapply(df, \(x) format(x, width = max(nchar(x)), scientific = FALSE)),
  file = "test.txt", 
  quote = FALSE,
  col.names = FALSE,
  row.names = FALSE)

Produces:

Stop    300
Go        6
Stop 800000
Go       20
Go     7000

Upvotes: 2

Jilber Urbina
Jilber Urbina

Reputation: 61204

Here's an approach:

df$c2 <- format(df$c2, scientific = FALSE)
n <- sapply(df, function(x) 6-nchar(x))

df2 <- df
for(j in seq_len(ncol(n))){
  for(i in seq_len(nrow(n))){
    df2[i,j] <- paste0(df2[i,j], paste0(rep(" ", n[i,j]), collapse = ""))
  }
}

write.table(df2, file = "test.txt", 
            quote = FALSE, 
            col.names = FALSE,
            row.names = FALSE)

output from txt file

Stop      300
Go          6
Stop   800000
Go         20
Go       7000

Upvotes: 1

Related Questions