Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

scan
scan() function
r
communitycreator

What is the scan() function in R?

AKASH BAJWA

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

This scan() function in R reads data as a list or vector that takes user input through a console or file.

scan(file, what, ...)

Parameters

This function takes the following arguments.

  • file: It is the text file to be scanned.
  • what: It is the type of input according to the value to be scanned. This argument has the following data types: raw, integer, logical, numeric, complex, character, and list.
  • ...: It represents additional optional arguments.

Return value

This method returns a list of vectors with types according to the what argument.

Code examples

Let’s learn this method in detail with some coding examples.

# Take the input from the keyboard
mylist <- scan()
# Print the output to the console
print(mylist)
  • Line 2: mylist <- scan() takes real numbers in the mylist variable from the user/keyboard.
  • Line 4: We print the input list to the console.
main.r
file.txt
# Demo program to use scan() for files
# Creating a data frame by using data.frame()
data <- data.frame(x1 = c(1, 2, 2, 3),
x2 = c(4, 5, 6, 7),
x3 = c(8, 9, 10, 11))
# Writing data to file.txt in the current directory
write.table(data,
file = "file.txt",
row.names = FALSE)
# Applying the scan function to the txt file
data <- scan("file.txt", what = list("", "", ""))
print(data)
Using the scan() function

Explanation

main.r

  • Line 3: We create a data frame using data.frame().
  • Line 7: We use write.table() to write the data into the mentioned file.
  • Line 11: We use the scan() function to read the data from the mentioned file.
  • Line 12: We print the data to the console.

file.txt

This is a sample file to show the program’s working.

RELATED TAGS

scan
scan() function
r
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring