How Can I Use the scan() Function in R?

The scan() function in R allows users to read data from external files or user input. It takes in arguments such as the file name and data type and returns the data in a vector or matrix format. For example, if we have a text file with numeric data, we can use the scan() function to read the data into R and perform various operations on it. This function is useful for importing data from various sources and manipulating it for analysis or visualization purposes.


You can use the scan() function in R to read data from a file into a vector or list.

This function uses the following basic syntax:

scan(file = “”, what = double(), …)

where:

  • file: The name of the file to read the data from.
  • what: The type of data to be read.

Refer to the R for a complete list of additional arguments you can use with the scan() function.

The following example shows how to use the scan() function in practice.

Example: How to Use scan() Function in R

Suppose I have a CSV file called data.csv saved in the following location:

C:UsersBobDesktopdata.csv

And suppose the CSV file contains the following data:

team, points, assists
'A', 78, 12
'B', 85, 20
'C', 93, 23
'D', 90, 8
'E', 91, 14

You can use the scan() function with the following code to quickly read the data from this file into R:

#read in data.csv into list
data <- scan("C:\Users\Bob\Desktop\data.csv", what = list("", "", ""))

#view data
data

[[1]]
[1] "team" "A"    "B"    "C"    "D"    "E"   

[[2]]
[1] "points" "78"     "85"     "93"     "90"     "91"    

[[3]]
[1] "assists" "12"      "20"      "23"      "8"       "14"

The scan() function has successfully read the data from the file into a list.

We can verify that this object is a list by using the class() function:

#view class of data object
class(data)

[1] "list"

Additional Resources

The following tutorials explain how to import other file types into R:

 

 

x