R에서 readlines() 함수를 사용하는 방법(예제 포함)


R의 readLines() 함수는 연결 개체에서 텍스트 줄 전체 또는 일부를 읽는 데 사용할 수 있습니다.

이 함수는 다음 구문을 사용합니다.

 readLines(con, n=-1L)

금:

  • 단점: 연결 개체 또는 문자열
  • n: 읽을 최대 줄 수입니다. 기본값은 모든 행을 읽는 것입니다.

다음 예에서는 some_data.txt 라는 텍스트 파일을 사용하여 실제로 이 함수를 사용하는 방법을 보여줍니다.

R의 readLines 함수

예제 1: readLines()를 사용하여 텍스트 파일의 모든 줄 읽기

내 컴퓨터의 문서 폴더에 텍스트 파일이 저장되어 있다고 가정해 보겠습니다.

다음 readLines() 함수를 사용하여 이 텍스트 파일의 각 줄을 읽을 수 있습니다.

 #read every line from some_data.txt
readLines("C:/Users/Bob/Documents/some_data.txt")

[1] “The first line of the file” “The second line of the file”
[3] “The third line of the file” “The fourth line of the file”
[5] "The fifth line of the file" "The sixth line of the file"  

텍스트 파일에는 6개의 라인이 포함되어 있으므로 readLines() 함수는 길이가 6인 문자형 벡터를 생성합니다.

원한다면 대신 데이터 프레임에 텍스트 파일의 줄을 저장할 수 있습니다.

 #read every line from some_data.txt
my_data <- readLines("C:/Users/Bob/Documents/some_data.txt")

#create data frame
df = data. frame (values=my_data)

#view data frame
df

                       values
1 The first line of the file
2 The second line of the file
3 The third line of the file
4 The fourth line of the file
5 The fifth line of the file
6 The sixth line of the file

결과는 1개의 열과 6개의 행으로 구성된 데이터 프레임입니다.

예제 2: readLines()를 사용하여 텍스트 파일의 처음 N 줄 읽기

텍스트 파일이 내 컴퓨터의 문서 폴더에 저장되어 있다고 다시 가정해 보겠습니다.

n 인수와 함께 다음 readLines() 함수를 사용하면 이 텍스트 파일의 처음 n 줄만 읽을 수 있습니다.

 #read first 4 lines from some_data.txt
readLines("C:/Users/Bob/Documents/some_data.txt", n= 4 )

[1] “The first line of the file” “The second line of the file”
[3] “The third line of the file” “The fourth line of the file”

readLines() 함수는 길이가 4인 문자형 벡터를 생성합니다.

또한 대괄호를 사용하여 이 텍스트 파일의 특정 줄을 탐색할 수도 있습니다.

예를 들어, 다음 코드를 사용하여 문자형 벡터의 두 번째 라인에만 액세스할 수 있습니다.

 #read first 4 lines from some_data.txt
my_data <- readLines("C:/Users/Bob/Documents/some_data.txt", n= 4 )

#display second line only
my_data[2]

[1] "The second line of the file"

추가 리소스

다음 튜토리얼에서는 다른 파일 형식을 R로 가져오는 방법을 설명합니다.

R에서 read.table을 사용하는 방법
CSV 파일을 R로 가져오는 방법
Excel 파일을 R로 가져오는 방법

의견을 추가하다

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다