R에서 단일 열의 이름을 바꾸는 방법(예제 포함)


다음 방법 중 하나를 사용하여 R의 데이터 프레임에 있는 단일 열의 이름을 바꿀 수 있습니다.

방법 1: Base R을 사용하여 단일 열 이름 바꾸기

 #rename column by name
colnames(df)[colnames(df) == ' old_name '] <- ' new_name '

#rename column by position
#colnames(df)[ 2 ] <- ' new_name '

방법 2: dplyr을 사용하여 단일 열 이름 바꾸기

 library (dplyr)

#rename column by name
df <- df %>% rename_at(' old_name ', ~' new_name ')

#rename column by position
df <- df %>% rename_at( 2 , ~' new_name ')

다음 예에서는 R의 다음 데이터 프레임을 사용하여 실제로 각 메서드를 사용하는 방법을 보여줍니다.

 #create data frame
df <- data. frame (team=c('A', 'B', 'C', 'D', 'E'),
                 points=c(99, 90, 86, 88, 95),
                 assists=c(33, 28, 31, 39, 34),
                 rebounds=c(30, 28, 24, 24, 28))

#view data frame
df

  team points assists rebounds
1 A 99 33 30
2 B 90 28 28
3 C 86 31 24
4 D 88 39 24
5 E 95 34 28

예시 1: Base R을 사용하여 단일 열 이름 바꾸기

다음 코드는 열 이름을 사용하여 points 열의 이름을 total_points 로 바꾸는 방법을 보여줍니다.

 #rename 'points' column to 'total_points'
colnames(df)[colnames(df) == ' points '] <- ' total_points '

#view updated data frame
df

  team total_points assists rebounds
1 A 99 33 30
2 B 90 28 28
3 C 86 31 24
4 D 88 39 24
5 E 95 34 28

다음 코드는 열 위치를 사용하여 points 열의 이름을 total_points 로 바꾸는 방법을 보여줍니다.

 #rename column in position 2 to 'total_points'
colnames(df)[ 2 ] <- ' total_points '

#view updated data frame
df

  team total_points assists rebounds
1 A 99 33 30
2 B 90 28 28
3 C 86 31 24
4 D 88 39 24
5 E 95 34 28

두 방법 모두 동일한 결과를 생성합니다.

예시 2: dplyr을 사용하여 단일 열 이름 바꾸기

다음 코드는 dplyrrename_at() 함수를 사용하여 포인트 열의 이름을 total_points 로 바꾸는 방법을 보여줍니다.

 library (dplyr)

#rename 'points' column to 'total_points' by name
df <- df %>% rename_at(' points ', ~' total_points ')

#view updated data frame
df

  team total_points assists rebounds
1 A 99 33 30
2 B 90 28 28
3 C 86 31 24
4 D 88 39 24
5 E 95 34 28

다음 코드는 dplyrrename_at() 함수를 사용하여 포인트 열의 이름을 열 위치별로 total_points 로 바꾸는 방법을 보여줍니다.

 library (dplyr)

#rename column in position 2 to 'total_points'
df <- df %>% rename_at( 2 , ~' total_points ')

#view updated data frame
df

  team total_points assists rebounds
1 A 99 33 30
2 B 90 28 28
3 C 86 31 24
4 D 88 39 24
5 E 95 34 28

두 방법 모두 동일한 결과를 생성합니다.

추가 리소스

다음 튜토리얼에서는 R에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.

R에서 특정 열을 선택하는 방법
R에서 특정 열을 보존하는 방법
R에서 여러 열을 기준으로 정렬하는 방법

의견을 추가하다

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