How to Print Something to the Screen in R?

Spread the love

Problem –

You want to print the value of a variable or expression.

Solution –

It is very easy to print something to the screen just type the variable name or expression at the command prompt and R will print it for you.

> pi
[1] 3.141593
> sqrt(4)
[1] 2

When you enter expression like these, R evaluates the expression and then implicitly calls the print function. The following expression is same as the above one.

> print(pi)
[1] 3.141593
> print(sqrt(4))
[1] 2

You can also use print to show matrices and list. print function knows how to display them to the user.

> print(matrix(c(1, 2, 3, 4), 2, 2))
     [,1] [,2]
[1,]    1    3
[2,]    2    4
> print(list("a","b","c"))
[[1]]
[1] "a"

[[2]]
[1] "b"

[[3]]
[1] "c"

But there is one limitation to print function. It only prints one item at a time. If you try to print multiple items together, it won’t work.

> print("Hello world", 2*pi)
[1] "Hello world"

The cat function is an alternative to print function that let’s you concatenate multiple items into a continuous output.

> cat("Hello world", 2*pi)
Hello world 6.283185

Rating: 1 out of 5.

Posted in RTagged

Leave a Reply