Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R scan() Function - Reading Data

R scan() Function - Reading Data

R Language Examples R Language Examples

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:

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"

)

print

(

"Values read:"

)

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

(

"Strings read:"

)

print

(

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 R Language Examples