Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading