Home > Back-end >  Recode data in an R dataframe column
Recode data in an R dataframe column

Time:11-14

I have a df with two columns: data and position, where: data are goals scored (1-10) and position is the position played (goalie, defence, forward)

I want to add a new column to the df, where if the position is "forward", for the row in a new column to say "good", otherwise, if it's "goalie" or "defence", for the row in the new column to say "bad" eg.

data position new.column
5 goalie bad
6 forward good
9 defence bad
5 forward good

CodePudding user response:

library(tidyverse)
df <- data.frame(data = c(5, 6, 9, 5), 
                 position = c('goalie', 'forward', 'defense', 'forward')) %>% 
mutate(new.column = case_when(
  position == 'forward' ~'good', 
  TRUE ~'bad'
))

  • Related