R scan() Function - Reading Data
The R scan() function is used to read data from a file or keyboard into a vector.
Unlike read.table(), scan() returns a vector rather than a data frame, making it suitable for reading streams of numeric data.
The syntax of the scan() function is as follows:
scan(file = "", what = double(), n = -1, sep = "", quiet = FALSE)
Parameter Description:
-
file A file path. When an empty string, reads from the keyboard.
-
what The data type, such as numeric() or character().
-
n The number of elements to read; -1 means read all.
-
sep The separator.
Example
First prepare a data file
writeLines
(
c
(
"10 20 30"
,
"40 50 60"
)
,
"temp_data.txt"
)
Read numeric values with scan
data
<-
scan
(
"temp_data.txt"
)
(
"Values read:"
)
(
data
)
(
paste
(
"Sum:"
,
sum
(
data
)
)
)
(
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
(
)
)
(
"Strings read:"
)
(
subjects
)
The output of the code above is:
Read 6 items
[1] "读取的数值:"
[1] 10 20 30 40 50 60
[1] "总和: 210"
[1] "均值: 35"
Read 5 items
[1] "读取的字符串:"
[1] "语文" "数学" "英语" "物理" "化学"
R Language Examples