Mutate() 및 case_when()을 사용하여 r에서 새 변수를 만듭니다.


특정 조건에 따라 R의 데이터 프레임에 새 변수를 생성하려는 경우가 종종 있습니다. 다행히 dplyr 패키지의 mutate()case_when() 함수를 사용하면 이 작업을 쉽게 수행할 수 있습니다.

이 튜토리얼에서는 다음 데이터 프레임과 함께 이러한 함수를 사용하는 몇 가지 예를 보여줍니다.

 #create data frame
df <- data.frame(player = c('a', 'b', 'c', 'd', 'e'),
                 position = c('G', 'F', 'F', 'G', 'G'),
                 points = c(12, 15, 19, 22, 32),
                 rebounds = c(5, 7, 7, 12, 11))

#view data frame
df

  player position points rebounds
1 to G 12 5
2 b F 15 7
3 c F 19 7
4 d G 22 12
5th G 32 11

예시 1: 기존 변수를 기반으로 새 변수 만들기

다음 코드는 포인트 열의 값을 기반으로 “scorer”라는 새 변수를 생성하는 방법을 보여줍니다.

 library(dplyr)

#define new variable 'scorer' using mutate() and case_when()
df %>%
  mutate (scorer = case_when (points < 15 ~ ' low ',
                           points < 25 ~ ' med ',
                           points < 35 ~ ' high '))

  player position points rebounds scorer
1 a G 12 5 low
2 b F 15 7 med
3 c F 19 7 med
4 d G 22 12 med
5th G 32 11 high

예 2: 여러 기존 변수를 기반으로 새 변수 만들기

다음 코드는 플레이어 및 위치 열의 값을 기반으로 “type”이라는 새 변수를 생성하는 방법을 보여줍니다.

 library(dplyr)

#define new variable 'type' using mutate() and case_when()
df %>%
  mutate (type = case_when (player == 'a' | player == 'b' ~ ' starter ',
                            player == 'c' | player == 'd' ~ ' backup ',
                            position == 'G' ~ ' reserve '))

  player position points rebounds type
1 a G 12 5 starter
2 b F 15 7 starter
3 c F 19 7 backup
4 d G 22 12 backup
5th G 32 11 reserve

다음 코드는 포인트 및 리바운드 열의 값을 기반으로 “valueAdded”라는 새 변수를 생성하는 방법을 보여줍니다.

 library(dplyr)

#define new variable 'valueAdded' using mutate() and case_when()
df %>%
  mutate (valueAdded = case_when (points <= 15 & rebounds <=5 ~ 2,
                                points <=15 & rebounds > 5 ~ 4,
                                points < 25 & rebounds < 8 ~ 6,
                                points < 25 & rebounds > 8 ~ 7,
                                points >=25 ~ 9))

  player position points rebounds valueAdded
1 to G 12 5 2
2 b F 15 7 4
3c F 19 7 6
4 d G 22 12 7
5th G 32 11 9

추가 리소스

R에서 열 이름을 바꾸는 방법
R에서 열을 삭제하는 방법
R에서 행을 필터링하는 방법

의견을 추가하다

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