R语言 从文件中读取行数 – readLines()函数

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
R

输出

[1] "the first line"  "the second line" "the third line"
R

例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
R

输出

[1] "the first line"  "the second line"
R

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册