R語言中的scan()函數用於掃描和讀取數據。它通常用於在 R 語言中將數據讀入向量或列表或文件中。
用法:
scan(“data.txt”, what = “character”)
參數:
數據.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() 函數從用戶那裏獲取輸入並打印值。
相關用法
- R語言 read.csv()用法及代碼示例
- R語言 read.table()用法及代碼示例
- R語言 readLines()用法及代碼示例
- R語言 data.matrix()用法及代碼示例
- R語言 with()用法及代碼示例
- R語言 sample()用法及代碼示例
- R語言 cat()用法及代碼示例
- R語言 all_equal()用法及代碼示例
- R語言 type.convert()用法及代碼示例
- R語言 is.character()用法及代碼示例
- R語言 expand.grid()用法及代碼示例
注:本文由純淨天空篩選整理自kaurbal1698大神的英文原創作品 Scan and Read Data from a File in R Programming – scan() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。