Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to print and cat

Tags:

r

Having a bit of a mental block. I am sure I found a function to print iteration numbers in a for loop that was not print and not cat, but gave the same output as cat below.

> for(i in 10^(1:5))  print(i)
[1] 10
[1] 100
[1] 1000
[1] 10000
[1] 1e+05
> for(i in 10^(1:5))  cat(i, "\n")
10 
100 
1000 
10000 
1e+05 

I cannot see any reference to it in the R help files for print and cat. Tried googling for it, but not getting anywhere.

like image 967
guyabel Avatar asked Jun 27 '12 16:06

guyabel


People also ask

What is the difference between print () and cat ()?

print() returns a character vector. A vector is an object in R language. cat() returns an object NULL . cat() returns an object NULL .

What is the difference between cat and paste in R?

The cat() function is typically more frequently used for troubleshooting. The paste() function, on the other hand, is used when you want to save the concatenation's results in a character variable and later refer to that variable in your code.

What does print () do in R?

R print() Function In the above example, we have used the print() function to print a string and a variable. When we use a variable inside print() , it prints the value stored inside the variable.

What is the difference between print and paste in R?

The difference between: paste and paste0 is that paste function provides a separator operator, whereas paste0 does not. print ()- Print function is used for printing the output of any object in R. This recipe demonstrates an example on paste, paste0 and print function in R.


2 Answers

It's easy enough to define a wrapper function around cat:

catn <- function(x, append="\n"){cat(x); cat(append)}

Use it:

for(i in 10^(1:5))  catn(i)
10
100
1000
10000
1e+05

Or you can use message (which has the added benefit that in some code editors, e.g. Eclipse, the messages appear in a different colour):

for(i in 10^(1:5))  message(i)
10
100
1000
10000
1e+05
like image 181
Andrie Avatar answered Oct 31 '22 12:10

Andrie


Turns out write can also write to standard output too if file == "":

> for (i in 10^(1:5)) write(i, "")
10
100
1000
10000
1e+05

The default value of file is "data" though.

(I am also searching for this missing operator for a long time :D)

like image 3
Hristo Iliev Avatar answered Oct 31 '22 12:10

Hristo Iliev