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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。