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.
print() returns a character vector. A vector is an object in R language. cat() returns an object NULL . cat() returns an object NULL .
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.
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.
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With