Open In App
Related Articles

Read Lines from a File in R Programming – readLines() Function

Improve Article
Improve
Save Article
Save
Like Article
Like

readLines() function in R Language reads text lines from an input file. The readLines() function is perfect for text files since it reads the text line by line and creates character objects for each of the lines.

Syntax: readLines(path)

Parameter:
path: path of the file

Example 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


Output:

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

Example 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


Output:

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

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 01 Jul, 2020
Like Article
Save Article
Previous
Next
Similar Reads