R语言 扫描并从文件中读取数据 – scan() 函数
R语言中的 scan() 函数是用来扫描和读取数据的。在R语言中,它通常用于将数据读入向量、列表或从文件中读取。
语法:
scan(“data.txt”, what = “character”)
参数:
data.txt: 要扫描的文本文件
返回: 扫描的输出
例子1: 扫描文本
# R Program to scan a file
# Create example data.frame
data <- data.frame(x1 = c(1, 2, 2, 3),
x2 = c(4, 5, 6, 7),
x3 = c(8, 9, 10, 11))
data
# Write data as txt file to directory
write.table(data,
file = "data.txt",
row.names = FALSE)
# Get currently used directory
getwd()
# Apply scan function to txt file
data <- scan("data.txt", what = "character")
data
输出:
x1 x2 x3
1 1 4 8
2 2 5 9
3 2 6 10
4 3 7 11
[1] "/home/cg/root/8121844"
[1] "x1" "x2" "x3" "1" "4" "8" "2" "5" "9" "2" "6" "10" "3" "7" "11"
Read 15 items
例2: 扫描数据为文本
# R Program to scan a file
# Create example data.frame
data <- data.frame(x1 = c(1, 2, 2, 3),
x2 = c(4, 5, 6, 7),
x3 = c(8, 9, 10, 11))
data
# Write data as txt file to directory
write.table(data,
file = "data.txt",
row.names = FALSE)
# Read txt file into list
data <- scan("data.txt", what = list("", "", ""))
data
输出
x1 x2 x3
1 1 4 8
2 2 5 9
3 2 6 10
4 3 7 11
[[1]]
[1] "x1" "1" "2" "2" "3"
[[2]]
[1] "x2" "4" "5" "6" "7"
[[3]]
[1] "x3" "8" "9" "10" "11"
Read 5 records
例3: 用扫描功能跳行
# R Program to scan a file
# Create example data.frame
data <- data.frame(x1 = c(1, 2, 2, 3),
x2 = c(4, 5, 6, 7),
x3 = c(8, 9, 10, 11))
data
# Write data as txt file to directory
write.table(data,
file = "data.txt",
row.names = FALSE)
# Skip first line of txt file
data <- scan("data.txt", skip = 1)
data
输出
x1 x2 x3
1 1 4 8
2 2 5 9
3 2 6 10
4 3 7 11
[1] 1 4 8 2 5 9 2 6 10 3 7 11
Read 12 items
例4: 扫描Excel CSV文件
# R Program to scan a file
# Create example data.frame
data <- data.frame(x1 = c(1, 2, 2, 3),
x2 = c(4, 5, 6, 7),
x3 = c(8, 9, 10, 11))
data
# Write data as csv file to directory
write.table(data,
file = "data.csv",
row.names = FALSE)
# Apply scan function to csv file
data <- scan("data.csv", what = "character")
data
输出
x1 x2 x3
x1 x2 x3
1 1 4 8
2 2 5 9
3 2 6 10
4 3 7 11
Read 15 items
[1] "x1" "x2" "x3" "1" "4" "8" "2" "5" "9" "2" "6" "10" "3" "7" "11"
例5: 从键盘上读取输入。
# take input from keyboard
z <- scan()
1
2
3
4
# print output on the screen
print(z)
输出
Read 4 items
[1] 1 2 3 4
在这里,在上述代码中,scan()函数将接受用户的输入,并使用print()函数打印数值。