Trying to Use Mutate and Ifelse to Create a New Column

Hi there, I am a new R coder and am working on a personal project related to soccer. I imported a dataset from Excel including goals scored by certain soccer players. I am trying to create a new column where each player gets a certain number of points for the amount of goals he scored...
<= 5 goals: 0 points
6 to 11 goals: 50 points
12 to 17 goals: 100 points
18+ goals: 150 points

I tried using the mutate and ifelse functions as seen here:

library(dplyr)
library(ggplot2)
library(tidyverse)

goldenboy <- read.csv("goldenboy.csv")

goldenboy <- goldenboy %>%
  mutate(CS_goals = ifelse(goals <= 5, 0,
                        ifelse(goals > 5 && goals < 12, 50,
                        ifelse(goals > 11 && goals < 18, 100,
                        ifelse(goals >= 18, 150, 0))))
         )```

Here is the resulting dataframe which incorrectly outputs 0 for each player:

As I mentioned, I am a new user of R and any help would be greatly appreciated!

Thanks!

Hi @saiftee13,
Since you're already using the tidyverse, I'd encourage you to check out the case_when() function. It's a vectorized ifelse that does pretty much exactly what you're trying to do.

I'm in a hurry right now and don't have time to write up a longer example, but I'll come back to this later and would be happy to help more if you're still stuck after checking out the documentation for that function.

Good luck!

Thanks for your input. I looked into the case_when() function and got it to work with my dataset.

Appreciate the quick response!

Thanks

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.