readLines()
R 語言中的函數從輸入文件中讀取文本行。這readLines()
函數非常適合文本文件,因為它逐行讀取文本並為每一行創建字符對象。
用法: readLines(path)
參數:
path:文件路徑
範例1:
# R program to illustrate
# readLines() function
# Store currently used directory
path <- getwd()
# Write example text to currently used directory
write.table(x = "the first line\nthe second line\nthe third line",
file = paste(path, "/my_txt.txt", sep = ""),
row.names = FALSE, col.names = FALSE, quote = FALSE)
# Apply readLines function to txt file
my_txt <- readLines(paste(path, "/my_txt.txt", sep = ""))
my_txt
輸出:
[1] "the first line" "the second line" "the third line"
範例2:
# R program to illustrate
# readLines() function
# Store currently used directory
path <- getwd()
# Write example text to currently used directory
write.table(x = "the first line\nthe second line\nthe third line",
file = paste(path, "/my_txt.txt", sep = ""),
row.names = FALSE, col.names = FALSE, quote = FALSE)
# Apply readLines function to first two lines
my_txt_ex2 <- readLines(paste(path, "/my_txt.txt", sep = ""),
n = 2)
my_txt_ex2
輸出:
[1] "the first line" "the second line"
相關用法
- R語言 read.csv()用法及代碼示例
- R語言 lines()用法及代碼示例
- R語言 read.table()用法及代碼示例
- R語言 scan()用法及代碼示例
- R語言 abline()用法及代碼示例
- R語言 cat()用法及代碼示例
- R語言 is.primitive()用法及代碼示例
注:本文由純淨天空篩選整理自akhilsharma870大神的英文原創作品 Read Lines from a File in R Programming – readLines() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。