Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

dataframe - Print a data frame with columns aligned (as displayed in R)

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="", 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="", 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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could also use capture.output with cat

cat(capture.output(dframe), file = 'dframe.txt', sep = '
')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...