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?
CodePudding user response:
One option would be to use e.g. stringr::str_pad
to add the padding spaces before exporting your table. I also added a format
so that the numerics don't get exported using scientific notation:
c1 <- c("Stop", "Go", "Stop", "Go", "Go")
c2 <- c(300,6,800000,20,7000)
df <- data.frame(c1, c2)
df$c1 <- stringr::str_pad(df$c1, 4, pad = " ", side = "right")
df$c2 <- stringr::str_pad(format(df$c2, scientific = FALSE), 6, pad = " ", side = "left")
df
#> c1 c2
#> 1 Stop 300
#> 2 Go 6
#> 3 Stop 800000
#> 4 Go 20
#> 5 Go 7000
write.table(df, file = "test.txt",
quote = FALSE,
col.names = FALSE,
row.names = FALSE)
CodePudding user response:
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
CodePudding user response:
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