4

I want to print a summary table(self-formatted) in R. So These summaries contain multiple lines and I'm working with RStudio and RScripts. So if I execute a statement like this:

print("Line 1")
print("Line 2")

I would like to have an output like

Line 1
Line 2

Instead I'm getting

> print("Line 1")
[1] "Line 1"
> print("Line 2")
[1] "Line 2"

What method could help or what do I have to do to achieve the desired output?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
MichiZH
  • 5,587
  • 12
  • 41
  • 81

2 Answers2

13

This will do what you are looking for cat("Line 1 \nLine 2")

 >cat("Line 1 \nLine 2")
 Line 1 
 Line 2

See R - do I need to add explicit new line character with print()?

Community
  • 1
  • 1
TylerDurden
  • 1,632
  • 1
  • 20
  • 30
  • ok this does it. However is there a method to enter it in the Editor line by line without using the \n? Because some summaries I'm printing are very complex with like 20-50 lines and using \n all the time makes it very hard to read in the script editor.. – MichiZH Aug 15 '13 at 07:51
  • oh and another question: how can I implement a variable containing a string withing line 1 and line 2? – MichiZH Aug 15 '13 at 07:56
  • would something like this help where you kept pasting the strings together with the new line character as the `sep` argument `cat(paste("Line 1","Line 2",sep="\n"))`. If you keep pasting the strings in a loop together to create a larger character vector – TylerDurden Aug 15 '13 at 07:57
  • Thank you, this was helpful. I would also like to add that in environments like Google Colab where all the results in a for loop are printed in one line, one could also simply add `"\n"` in the end for the next iteration of the loop to be printed in the next line. For example: `for (n in 1:25)` `cat("Func1", func1(n), "\n")` – BoyAcc Jun 21 '22 at 07:37
0

I think the easiest way is

dataframe[1:2,]

where dataframe = name of your dataset (assuming you are using tabular data).

In this case, you print the first two rows, and all columns (by leaving the second element in the vector empty).

kwoxer
  • 3,734
  • 4
  • 40
  • 70