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

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-29 06:43:47

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)

You could also use capture.output with cat

cat(capture.output(dframe), file = 'dframe.txt', sep = '\n')
# 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)
jpjns

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

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

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.

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