I need to create one column which is base on other two columns. The thing is I don't want to use rowwise because it makes it too slow when used on large data, when I don't use rowwise it does not work.
library(tidyverse)
df <- tibble(
param1 = c(NA, "---", "< 2,8", "5", "6", "7", "-"),
param2 = c("---", "4", "5.5", "6", NA, "< 10,8", "6")
)
# A tibble: 7 x 2
param1 param2
<chr> <chr>
1 NA ---
2 --- 4
3 < 2,8 5.5
4 5 6
5 6 NA
6 7 < 10,8
7 - 6
desired_output:
# A tibble: 7 x 3
# Rowwise:
param1 param2 param3
<chr> <chr> <chr>
1 NA --- NA
2 --- 4 NA
3 < 2,8 5.5 6.9
4 5 6 11
5 6 NA NA
6 7 < 10,8 12.4
7 - 6 NA
This is what I tried so far, which produces the correct output, but as I said, it is slow because of rowwise, is there another fast vectorized option?. I'm open to other approaches. Thanks.
somefunction <- function(value) {
parse_number(str_remove(str_replace(value, ",", "."), "<")) * (as.numeric(!str_detect(value, "<")) + 1)/2
}
df %>%
rowwise() %>%
mutate(
param3 = case_when(
is.na(param1) || is.na(param2) || str_detect(param1, "^-") || str_detect(param2, "^-") ~ NA_character_,
TRUE ~ as.character(somefunction(param1) + somefunction(param2))
)
)