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을 사용하여 단일 열 이름 바꾸기
다음 코드는 dplyr 의 rename_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
다음 코드는 dplyr 의 rename_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에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.