當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


R語言 readLines()用法及代碼示例


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"



相關用法


注:本文由純淨天空篩選整理自akhilsharma870大神的英文原創作品 Read Lines from a File in R Programming – readLines() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。