📜  在 R 编程中从文件中读取行 – readLines()函数

📅  最后修改于: 2022-05-13 01:54:55.732000             🧑  作者: Mango

在 R 编程中从文件中读取行 – readLines()函数

R 语言中的readLines()函数从输入文件中读取文本行。 readLines()函数非常适合文本文件,因为它逐行读取文本并为每一行创建字符对象。

示例 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"