Home > OS >  Using the same variable within str_detect and mutate
Using the same variable within str_detect and mutate

Time:02-19

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?

CodePudding user response:

I've created a dummy dataframe to demonstrate.

Since your time_col is character, you'll need to first get rid of the string " minutes" (note the space before "minutes"), change it to numeric, then divide it by 60.

Input

library(tidyverse)

df <- data.frame(Dummy = letters[1:3], 
                 time_col = c("2", "20 minutes", "30 minutes"))

df
  Dummy   time_col
1     a          2
2     b 20 minutes
3     c 30 minutes

Code and output

df %>% mutate(time_col = ifelse(
  str_detect(time_col, "minutes"),
  as.numeric(gsub(" minutes", "", time_col)) / 60,
  time_col
))

  Dummy          time_col
1     a                 2
2     b 0.333333333333333
3     c               0.5
  • Related