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()
and write.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)
You could also use capture.output
with cat
cat(capture.output(dframe), file = 'dframe.txt', sep = '\n')