R scan() Function - Reading Data

R 语言实例R Language Examples

The R scan() function is used to read data from a file or keyboard into a vector.

Unlike read.table(), scan() directly returns a vector rather than a data frame, making it suitable for reading numeric data streams.

The syntax of the scan() function is as follows:

scan(file = "", what = double(), n = -1, sep = "", quiet = FALSE)

Parameter description:

  • fileFile path. When it is an empty string, reads from the keyboard.

  • whatData type, such as numeric() or character().

  • nNumber of elements to read; -1 means read all.

  • sepSeparator.

Example

# First prepare a data file
writeLines(c("10 20 30", "40 50 60"), "temp_data.txt")

# Use scan to read numeric values
data <- scan("temp_data.txt")
print("Read values:")
print(data)
print(paste("Sum:", sum(data)))
print(paste("Mean:", mean(data)))

# scan can also read strings directly
writeLines(c("Chinese Math English Physics Chemistry"), "temp_subjects.txt")
subjects <- scan("temp_subjects.txt", what = character())
print("Read strings:")
print(subjects)

Executing the above code outputs the following result:

Read 6 items
[1] "读取的数值:"
[1] 10 20 30 40 50 60
[1] "总和: 210"
[1] "均值: 35"
Read 5 items
[1] "读取的字符串:"
[1] "语文" "数学" "英语" "物理" "化学"

R 语言实例R Language Examples

Other extensions