R语言 从文件中读取行数 – readLines()函数
R语言中的 readLines() 函数从一个输入文件中读取文本行。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"