'Using the same variable within str_detect and mutate

I have a variable time_col which contains the word 'minutes' if it is in minutes (e.g. 20 minutes), and only contains a number if it in hours (e.g. 2). I want to remove the word 'minutes' and convert it into hours when the observation is in minutes.

df <- raw_df %>%
      mutate(time_col = ifelse(str_detect(time_col, "minutes"), time_col/60, time_col))

However, this gives an error:

'Error: Problem with `mutate()` input `time_col`. x non-numeric argument to binary operator.'

I don't have this issue when I use ifelse(str_detect(time_col, "minutes"), 1, 0) so I think this is because the str_detect replaces time_col before going over to the ifelse condition.

How do I fix this issue?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source