使用 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