Basic Input and Output Functions in R

 

Basic Input and Output Functions in R

Input and output operations enable a program to communicate with users and external files. R provides several built-in functions for displaying information and accepting input.


1. print() Function

The print() function displays the value of an object. It automatically adds index numbers and quotes for strings.

Syntax

print(object)

Example

name <- "Alice"
age <- 20

print(name)
print(age)

Output

[1] "Alice"
[1] 20

2. cat() Function

The cat() (concatenate) function prints formatted output without index numbers or quotation marks.

Syntax

cat(object1, object2, ...)

Example

name <- "Alice"
age <- 20

cat("Name:", name, "\n")
cat("Age:", age)

Output

Name: Alice
Age: 20

Uses

  • Printing multiple values together.
  • Formatting output.
  • Adding spaces and line breaks.

3. message() Function

The message() function displays informational messages. It is mainly used to provide status information, warnings, or debugging messages.

Syntax

message(text)

Example

message("Program started successfully.")

Output

Program started successfully.

Example

name <- "John"

message("Welcome ", name)

Output

Welcome John

Uses

  • Displaying progress messages.
  • Indicating successful execution.
  • Debugging programs.

4. sprintf() Function

The sprintf() function formats strings in a manner similar to C programming.

Syntax

sprintf(format, values)

Common Format Specifiers

SpecifierMeaning
%dInteger
%fFloating-point number
%.2fFloating-point number with two decimal places
%sString

Example 1: Formatting Integers

age <- 21

sprintf("Age = %d years", age)

Output

[1] "Age = 21 years"

Example 2: Formatting Decimal Numbers

pi <- 3.141592

sprintf("Value of pi = %.2f", pi)

Output

[1] "Value of pi = 3.14"

Example 3: Multiple Variables

name <- "Alice"
marks <- 95.5678

sprintf("Student %s scored %.1f marks", name, marks)

Output

[1] "Student Alice scored 95.5 marks"

5. readline() Function

The readline() function accepts input from the keyboard. By default, the input is stored as a character string.

Syntax

variable <- readline(prompt)

Example

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

print(name)

Sample Input

Enter your name: John

Output

[1] "John"

6. scan() Function

The scan() function reads multiple values from the keyboard.

Syntax

variable <- scan()

Example

numbers <- scan()

print(numbers)

Input

10 20 30 40

Output

Read 4 items
[1] 10 20 30 40


Uses of scan()

Reading multiple values from the keyboard in a single statement.
Creating numeric, character, or logical vectors interactively.
Reading data from text files.
Accepting sequences of numbers for statistical computations.
Simplifying input when many values need to be entered together.

Example 1: Reading Numeric Values

numbers <- scan()
print(numbers)

Input

10 20 30 40 50

Output

Read 5 items
[1] 10 20 30 40 50

Here, scan() reads all values entered and stores them in a numeric vector.


Example 3: Reading Character Values

names <- scan(what = character())
print(names)

Input

John Mary Alice David

Output

Read 4 items
[1] "John" "Mary" "Alice" "David"

Use of what in scan()

The what argument specifies the type of data to be read. By default, scan() reads numeric

values. To read other types of data, the appropriate value should be supplied to what.

Syntax

scan(what = data_type)

where data_type can be:

what ValueData Type Read
numeric()    Numeric values
integer()    Integer values
character()    Character strings
logical()    Logical values (TRUE/FALSE)
complex()    Complex numbers

Example 4: Reading Integers

nums <- scan(what = integer())
print(nums)

Input

5 10 15 20

Output

Read 4 items
[1] 5 10 15 20

Example 5: Reading Logical Values

flags <- scan(what = logical())
print(flags)

Input

TRUE FALSE TRUE

Output

Read 3 items
[1] TRUE FALSE TRUE

Example 6: Reading Data from a File

Suppose numbers.txt contains:

12 24 36 48
data <- scan("numbers.txt")
print(data)

Output

Read 4 items
[1] 12 24 36 48

Summary of scan()

FeatureDescription
Purpose    Reads multiple values at once
Default Data Type    Numeric
Return Value    Vector
Input Source    Keyboard or file
what Argument    Specifies the data type to read
Common Uses    Creating vectors, reading datasets, interactive input

Example Program

# Reading student names
print(Enter student names:)
names <- scan(what = character())


# Reading marks

print("Enter marks:")
marks <- scan()

print(names)
print(marks)

Sample Input

Enter student names:
John Mary Alex

Enter marks:
80 90 75

Output

Read 3 items
Read 3 items

[1] "John" "Mary" "Alex"
[1] 80 90 75

7. paste() Function

The paste() function combines strings and values together.

Example

name <- "John"
age <- 20

msg <- paste("Name =", name, "Age =", age)

print(msg)

Output

[1] "Name = John Age = 20"

8. paste0() Function

The paste0() function concatenates strings without spaces.

Example

x <- 100

paste0("Value=", x)

Output

[1] "Value=100"

Comparison of Output Functions

FunctionPurposeOutput Style
print()    Displays objects            Includes index numbers and quotes
cat()    Formatted output    No quotes or index numbers
message()    Informational messages    Useful for status/debugging
sprintf()    Formatted strings    Precise control over output
paste()    Concatenates strings    Returns a string with spaces
paste0()    Concatenates strings    Returns a string without spaces

Complete Example

# Input
name <- readline("Enter your name: ")
marks <- as.numeric(readline("Enter marks: "))

# Output
print(name)

cat("Marks =", marks, "\n")

message("Data entered successfully.")

msg <- sprintf("Student %s scored %.2f marks", name, marks)

print(msg)

Sample Execution

Enter your name: Alice
Enter marks: 89.75

[1] "Alice"
Marks = 89.75
Data entered successfully.
[1] "Student Alice scored 89.75 marks"

Summary of Basic Input and Output Functions

FunctionPurpose
print()    Displays objects and values
cat()    Displays formatted output
message()    Displays informational messages
sprintf()    Creates formatted strings
readline()        Reads a single input
scan()    Reads multiple inputs
paste()    Concatenates strings with spaces
paste0()    Concatenates strings without spaces
read.csv()    Reads data from a CSV file
write.csv()    Writes data to a CSV file

Conclusion

R provides a rich set of input and output functions for interacting with users and files. Functions such as print(), cat(), message(), and sprintf() help present information in different formats, while readline() and scan() enable interactive input. These functions form the foundation for developing user-friendly and data-driven R programs.

Comments

Popular posts from this blog

Statistical Methods Lab ( R Language) PCCBL308 Semester 3 KTU BTech CB and CU 2024 Scheme - Dr Binu V P

Sample Programs to Explore Basic Concepts in R