I'm struggling understanding why my code below works only when using rowwise in combination with ifelse. Or more precisely, I think I get why it is working in that scenario, but not why it doesn't simply work with if_else.
What I'm doing is, I'm checking if a certain rows contains the word "infile" or "outfile" and if it has a relative path (".."). If it does have the words "infile/outfile" and not a relative path, then it has an absolute path "C:". And in that case, I want to replace the user name with something else (here: "test").
Any ideas?
Data:
df <- structure(list(value = c("infile 'C:\\Users\\USER\\folder\\Data.sav'",
"infile '..\\folder\\Data.sav'", "outfile '..\\folder\\Data.sav'",
"test", "")), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-5L))
user_name <- "test"
Code that works:
df |>
rowwise() |>
mutate(value = ifelse(str_detect(value, "infile|outfile") & !str_detect(value, "\\'\\.\\.\\\\"),
str_replace(value,
str_sub(value,
str_locate_all(value, "\\\\")[[1]][2] + 1,
str_locate_all(value, "\\\\")[[1]][3] - 1),
user_name),
value)) |>
ungroup()
with output:
# A tibble: 5 × 1
value
<chr>
1 "infile 'C:\\Users\\test\\folder\\Data.sav'"
2 "infile '..\\folder\\Data.sav'"
3 "outfile '..\\folder\\Data.sav'"
4 "test"
5 ""
Code that doesn't work:
df |>
mutate(value = if_else(str_detect(value, "infile|outfile") & !str_detect(value, "\\'\\.\\.\\\\"),
str_replace(value,
str_sub(value,
str_locate_all(value, "\\\\")[[1]][2] + 1,
str_locate_all(value, "\\\\")[[1]][3] - 1),
user_name),
value))
I think this works, but gives a warning message:
Warning messages:
1: Problem while computing `value = if_else(...)`.
ℹ empty search patterns are not supported
2: Problem while computing `value = if_else(...)`.
ℹ empty search patterns are not supported
Code that doesn't work:
df |>
rowwise() |>
mutate(value = if_else(str_detect(value, "infile|outfile") & !str_detect(value, "\\'\\.\\.\\\\"),
str_replace(value,
str_sub(value,
str_locate_all(value, "\\\\")[[1]][2] + 1,
str_locate_all(value, "\\\\")[[1]][3] - 1),
user_name),
value)) |>
ungroup()
Error in `mutate()`:
! Problem while computing `value = if_else(...)`.
ℹ The error occurred in row 2.
Caused by error:
! Empty `pattern` not supported