This scan()
function in R reads data as a list or vector that takes user input through a console or file.
scan(file, what, ...)
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.This method returns a list of vectors with types according to the what
argument.
Let’s learn this method in detail with some coding examples.
# Take the input from the keyboardmylist <- scan()# Print the output to the consoleprint(mylist)
mylist <- scan()
takes real numbers in the mylist
variable from the user/keyboard.# 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 directorywrite.table(data,file = "file.txt",row.names = FALSE)# Applying the scan function to the txt filedata <- scan("file.txt", what = list("", "", ""))print(data)
main.r
data.frame()
.write.table()
to write the data into the mentioned file.scan()
function to read the data from the mentioned file.file.txt
This is a sample file to show the program’s working.