How can I use the scan() function in R?

The scan() function in R is a useful tool for reading data from external sources, such as files or databases, and converting it into a format that can be used for analysis. It allows for the user to specify the type of data to be read and the structure of the input, making it a versatile function for various data formats. For example, if a user wants to read a text file containing numerical data, they can specify the type as numeric and the structure as a vector. This function can be used in conjunction with other R functions to manipulate and analyze the data. An example of using the scan() function would be reading a CSV file with customer sales data and converting it into a data frame for further analysis. Overall, the scan() function provides a convenient and efficient way to import and process external data in R.

Use the scan() Function in R (With Example)


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:UsersBobDesktopdata.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