Home > Mobile >  Print R data frame one line per row
Print R data frame one line per row

Time:03-16

When using print to print data frames I find that it stops at some width, a bit short of 80 characters, and prints only those columns that can fit. Then it proceeds to print the next so-many columns.

Is is possible to get it to print a whole row, regardless of how wide, without newlines or dots, to the output?

CodePudding user response:

If you convert your data.frame to a tibble using df <- as_tibble(df), you have access to fine control the way you'd like to print your table:

library(tidyverse)

# example data
data <- iris %>% t() %>% as_tibble()

# print all columns
data %>% print(width = Inf)

# print all rows and all columns
data %>% print(width = Inf, n = Inf)

See also https://tibble.tidyverse.org/reference/formatting.html

However, there is a reason to only print the first rows and columns: It can get very messy and slow to print thousands of rows. You can also run View(data) to explore the table in a new window.

CodePudding user response:

Your comment on another answer suggests that you're doing this specifically to write out to a file - this answer does that, but the display may look different in the console depending on whether you're using R or Rstudio.

According to ?options there is a hard limit of 10,000 character width for the console, which can only be increased by recompiling R. If this is enough for your use case then you can do:

oldoptions <- options(width=10000)
options("width") #check that it's been set
#$width
#[1] 10000

sink("test.txt")  #append = TRUE might be useful for subsequent writes
print(a)  #Print the very wide dataframe
sink()

options(oldoptions) # reset the changed options

Note that initially I thought that this wasn't working when I inspected the file in Notepad - that was because (my setup of) Notepad has a limit on line length itself, and then wraps onto the next line. Viewing with something more sophisticated (Notepad ) shows that it did work sccessfully.

  • Related