Print a data frame with columns aligned (as displayed in R)
Solution 1
You could redirect the output of print
to file.
max.print <- getOption('max.print')
options(max.print=nrow(dframe) * ncol(dframe))
sink('dframe.txt')
dframe
sink()
options(max.print=max.print)
Solution 2
You could also use capture.output
with cat
cat(capture.output(dframe), file = 'dframe.txt', sep = '\n')
Solution 3
To control the output, tune print.data.frame
to your needs and capture the output to a file, eg.:
capture.output(
print.data.frame(df, row.names=F, print.gap=3, quote=F, right=F),
sep="\n", file="out.txt"
)
Solution 4
# Add the row names to the data frame, if you want them included
dframe2 <- data.frame("Row"=rownames(dframe), dframe, stringsAsFactors=FALSE)
# apply format over each column
dframe2 <- apply(dframe2, 2, format)
# print it out, make sure not to use quotes
write.table(dframe2, "test.txt", quote=FALSE, row.names=FALSE)
Solution 5
I liked the simplicity the answer of Matthew Plourde, but unfortunately, it does not offer a way to get rid of the row names/numbers for my situation; so, I modified a little bit the answer of Ricardo:
print.to.file <- function(df, filename) {
cnames <- colnames(df)
n <- as.matrix(nchar(cnames))
d <- apply(df, 2, format)
n <- apply(cbind(n, nchar(d[1,])), 1, max)
fmts <- paste0("%",n, "s")
for(i in 1:length(cnames)) {
cnames[i] <- sprintf(fmts[i], cnames[i])
d[,i] <- sprintf(fmts[i], trimws(d[,i]))
}
d <- rbind(cnames, d)
write.table(d, filename, quote=F, row.names=F, col.names=F)
}
This gives the same output of Matthew's except row names/numbers.
EDIT: replace trim
with trimws
.
Related videos on Youtube
terdon
Elected moderator on Unix & Linux. I've been using Linux since the late '90s and have gone through a variety of distributions. At one time or another, I've been a user of Mandrake, SuSe, openSuSe, Fedora, RedHat, Ubuntu, Mint, Linux Mint Debian Edition (basically Debian testing but more green) and, for the past few years, Arch. My Linux expertise, such as it is, is mostly on manipulating text and regular expressions since that represents a large chunk of my daily work.
Updated on June 04, 2022Comments
-
terdon almost 2 years
I have the following data frame in R:
> dframe Mean Median Candidates 85.68 60 NonCands 9.21 4 Multi 27.48 17 Mono 4.43 3 Multi NonCands 22.23 15
I want to print it into a file and keep it nicely formatted and aligned just as shown above. I use:
write.table(dframe,file="test",sep="\t", quote=F)
which produces the following output:
Mean Median Candidates 85.68 60 NonCands 9.21 4 Multi 27.48 17 Mono 4.43 3 Multi NonCands 22.23 15
Since the data is displayed properly formatted within the R environment I thought it should be trivial to write it to a file with the same format. Apparently I was wrong. I have tried playing with
format()
andwrite.matrix
from the MASS library but neither produces the desired result.I have seen some suggestions like this one, but it seems both too complicated and, more importantly, does not produce the desired result when printing to a file with
write.table()
.So, how can I print my data frame to a text file and have it look just as it does within R?
UPDATE
Following Justin's suggestion from his comment below, I installed the gdata library and used
write.fwf
. This is almost what I need:write.fwf(dframe,file="test",sep="\t", quote=F, rownames=T)
produces the following output:
Mean Median Candidates 85.68 60 NonCands 9.21 4 Multi 27.48 17 Mono 4.43 3 Multi NonCands 22.23 15
So, any ideas on how to get "Mean" and "Median" shifted to the right so they align with their respective columns?
Since it may now be relevant, here is how the data.frame was created:
labels<-c("Candidates","NonCands","Multi", "Mono", "Multi NonCands") Mean <- c(mean(cands), mean(non),mean(multi),mean(mono),mean(multi_non)) Median <- c(median(cands), median(non),median(multi),median(mono),median(multi_non)) names(Mean)<-labels dframe<-data.frame(Mean,Median)
-
Justin over 11 yearstake a look at
write.fwf
from thegdata
package.fwf
stands for fixed width file. however, if the font used to view a text file isn't fixed width, it might not be even.
-
-
Sezen almost 11 yearsYou may experience
getOption("max.print")
issue if the number of rows are greater thanmax.print
value. -
Sezen almost 11 years@MatthewPlourde, please see my answer below, is there a way to get rid of row names/numbers in your simple solution?
-
Matthew Plourde almost 11 years@Sezen You could convert the data.frame to a matrix and set them all to the empty character.
-
terdon almost 9 yearsHow does this print to a file?
-
jnas almost 9 yearsIt does not. I focused on the question of formatting the data frame.
-
terdon almost 9 yearsThanks, but the dataframe is displayed perfectly in R. The question is about printing it to a file, so your answer is not really relevant here.
-
jnas almost 9 years
capture.output
takes afile
parameter itself, too. -
jnas almost 9 yearsRewrote the answer completely
-
AF7 over 6 yearsUnfortunately in using the latest R...
Error in trim(d[, i]) : could not find function "trim"
-
Krister Janmore almost 3 years
sep="\n"
gives a "bad argument" error fromcapture.output()
for me in R 4.0.2. Dropping it seems to give fine output.