The readlines() function used to read text from a file or connection.
The following method shows how you can do it with syntax.
Method: Use readLines() Function
readLines(con,n=-1L)
con : A connection string or file path
n : Number of lines to read. By default it read all lines.
The following examples show how to use readLines() function in R.
Use readLines() to Read All Lines from Text File
Suppose we have sample.txt file in working directory with some data.
Use readLines() function to read all lines from this file and store in data frame:
# Read every line from sample.txt
data <- readLines("sample.txt")
# Create data frame
df = data.frame(values=data)
# Print data frame
print(df)
Output:
values
1 "Machine_name" "Pressure" "Temperature" "Status"
2 "1" "A" 78.2 31 TRUE
3 "2" "B" 71.7 35 TRUE
4 "3" "C" 80.21 36 FALSE
5 "4" "D" 83.12 36 FALSE
6 "5" "E" 82.56 38 FALSE
7 "6" "F" 79.5 32 TRUE
The output shows all lines from sample.txt file. The text file contains 6 lines, so the readLines() function produces data frame with 6 rows.
Use readLines() to Read Only N Specific Lines
Suppose we want to read only first 3 lines from sample.txt file:
# Read 4 lines from sample.txt
data <- readLines("sample.txt", n=3)
# Create data frame
df = data.frame(values=data)
# Print data frame
print(df)
Output:
values
1 "Machine_name" "Pressure" "Temperature" "Status"
2 "1" "A" 78.2 31 TRUE
3 "2" "B" 71.7 35 TRUE
As in the output only first 3 rows are read from text file using readLines() function.