Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 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 Answer

0 votes
by (71.8m points)

You could also use capture.output with cat

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...