0

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
Edcarm
  • 13
  • 1
  • `df$new.column <- ifelse(df$position == "forward", "good", "bad")`. Or the inverse (which might be informative for other needs): `ifelse(df$position %in% c("goalie","defence"), "bad", "good")`. For discussions on `==`-vs-`%in%`, see https://stackoverflow.com/q/15358006/3358272 and https://stackoverflow.com/q/42637099/3358272. – r2evans Nov 12 '21 at 21:57
  • 1
    For more complex recoding, there will be lots of answered questions around here already, e.g. https://stackoverflow.com/questions/5372896/recoding-variables-with-r/5373512#5373512 – jakub Nov 12 '21 at 21:57
  • @jakub, I think there's likely a better dupe-link out there; that one refers to recoding a numeric column whereas this data is recoding strings. – r2evans Nov 12 '21 at 21:59
  • 1
    @r2evans true. I spent a little while looking and haven't found a really good one. I think pointing out `ifelse()` and `dplyr::recode()` might just be enough though. – jakub Nov 12 '21 at 22:06

1 Answers1

0
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'
))

Susan Switzer
  • 1,531
  • 8
  • 34