0

I have a data frame with a column that contains text and a number of variables that contain values that correspond to the strength of that league. I want to create a new column in the same df that contains the corresponding variable value for each row.

I tried this:

prospects2020$leaguemod <- if(prospects2020$LEAGUE == "QMJHL") {
  QMJHLe
} else if (prospects2020$LEAGUE == "OHL") {
  OHLe
}else{
  WHLe
}

where QMJHLe, OHLe and WHLe are variables in my GE, and it creates the column but every value is equal to QMJHLe's value. I'm getting the error message:

Warning message:

In if (prospects2020$LEAGUE == "QMJHL") { : the condition has length > 1 and only the first element will be used

I feel like this should work but I'm pretty new to this. Maybe this is a wrong-headed way to accomplish what I am trying to do? How can I make it behave as I designed, or should I be using an entirely different approach?

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Jul 12 '20 at 01:20

1 Answers1

0

Assuming QMJHLe, OHLe and WHLe variables are of length 1, you can use ifelse here for vector values.

prospects2020$leaguemod  <- ifelse(prospects2020$LEAGUE == "QMJHL", QMJHLe, 
                              ifelse(prospects2020$LEAGUE == "OHL", OHLe, WHLe))

Or with case_when :

library(dplyr)
prospects2020 %>%
   mutate(leaguemod = case_when(LEAGUE == "QMJHL", ~ QMJHLe, 
                                LEAGUE == "OHL", ~OHLe, 
                                TRUE ~ WHLe))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • ifelse seems to be working when nested as you laid out (I had like a dozen other leagues to add), but the case_when option came up with an error saying the input couldn't be logical. – Ian McNamara Jul 12 '20 at 03:12
  • It depends on what you have in your data, I am glad `ifelse` works for you. – Ronak Shah Jul 12 '20 at 03:14