Take Input and Print in R

The <- symbol is the assignment operator. Assign some value to a variable then you can do either auto-printing for the variables just typing its name or you can use explicit printing.

msg <- "hello R!!!"
msg    #auto-printing occurs
print(msg) #explicit printing

Output:

msg
[1] "hello R!!!"
> print(msg)
[1] "hello R!!!"

Try it Yourself

Take Input From User:

When we are working with R in an interactive session, we can use readline() function to take input from the user.

name <- readline(prompt="Enter your name: ")

Output:

name <- readline(prompt="Enter your name: ")
Enter your name: Kalyan

print(name)

Output:

[1] "Kalyan"

Multiple inputs from user using R:

You can combine the statements into a clause like below to take multiple input from user.

{name <- readline(prompt="Enter your name: ");
age <- readline(prompt="Enter your age: ")}

#OR

{name <- readline("Enter your name: ");
age <- readline("Enter your age: ")}

Output:

{name <- readline(prompt="Enter your name: ");
+ age <- readline(prompt="Enter your age: ")}
Enter your name: Kalyan
Enter your age: '26'

print(name)
print(age)

Output:

print(name)
[1] "Kalyan"
> print(age)
[1] "26"

OR you can make them into a function like below. Both the above and below codes serve the same purpose. First define the function. The call the function.

readlines <- function(…) {
lapply(list(…), readline)
}

readlines("Enter your name: ","Enter your age: ")

Output:

[[1]]
[1] "Kalyan"

[[2]]
[1] “26”

Loading R Packages

R Objects and Attributes