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

北城余情 提交于 2019-11-30 08:19:42

问题


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)

回答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)



回答2:


You could also use capture.output with cat

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



回答3:


# 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)



回答4:


Another way without row names based on the answer of mnel:

prettyprint.df <- function(x, filename='dframe.txt', width=200)  
   # Pretty-print data frame without row names  
{  
   op.w <- options("width")  
   options("width"=width)  

   first <- max(nchar(rownames(x))) + 2  
   cat(substring(capture.output(x), first), file=filename, sep="\n")  

   options(op.w)  
}  



回答5:


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"
)



回答6:


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.



来源:https://stackoverflow.com/questions/13590887/print-a-data-frame-with-columns-aligned-as-displayed-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!