Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multiple str_replace functions within the same mutate()

my dummy code:

x <- c("A", "B", "C", "D")
y <- c("<0.5", "~1", "<10", "~30")

df <- data.frame(x,y) %>%
  mutate(y1 = str_replace(y, "~", ""),
         y2 = as.numeric(str_replace(y1, "<", ""))/2)

Basically what I want to do in column y is:

  • Remove the "~" from values that contain "~"
  • Remove "<" from values that contain "<", then halve those values

Ideally I'll come out with a fully numeric column.

How do I go about this step without needing the interim "y1" variable? I've tried putting both into str_replace but doesn't seem to work, or creates NAs. I've also tried piping within the str_replace but that doesn't work either. Note I only want the "<" values halved.

Thanks.

like image 515
tm95 Avatar asked Sep 23 '26 10:09

tm95


2 Answers

We can concatenate several remove conditions by the OR operator:

library(tidyverse)

df <- data.frame(x = c("A", "B", "C", "D"),
                 y = c("<0.5", "~1", "<10", "~30"))

df %>%
  mutate(y2 = as.numeric(str_remove(y, "<|~")),
         y2 = if_else(str_detect(y, '<'), 0.5 * y2, y2))

which gives:

  x    y    y2
1 A <0.5  0.25
2 B   ~1  1.00
3 C  <10  5.00
4 D  ~30 30.00

Updated solution by overwriting y:

df %>%
  mutate(y = if_else(str_detect(y, '<'), 0.5 * as.numeric(str_remove(y, "<|~")), as.numeric(str_remove(y, "<|~"))))

which gives:

  x     y
1 A  0.25
2 B  1.00
3 C  5.00
4 D 30.00

Of course you could also just delete the old y column from solution 1 and rename y2 to y.

like image 96
deschen Avatar answered Sep 25 '26 02:09

deschen


Update: See comment of op:

library(tidyverse)
df %>% 
  mutate(y = ifelse(str_detect(y, "<"), parse_number(y)/2, parse_number(y)))
  x     y
1 A  0.25
2 B  1.00
3 C  5.00
4 D 30.00

@deschen answer is good. An alternative is to use parse_number from readr package:

library(tidyverse)

df %>% 
  mutate(y2 = ifelse(str_detect(y, "<"), parse_number(y)/2, parse_number(y)))
  x    y    y2
1 A <0.5  0.25
2 B   ~1  1.00
3 C  <10  5.00
4 D  ~30 30.00
like image 29
TarJae Avatar answered Sep 25 '26 02:09

TarJae



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!