'Mutate condition multiple columns loop dplyr
I am trying to conditionnally replace values in one column based on the value from another column. The condition is simple, if a column's value equals "NAv" then I want to check the value in the neighboring column (left and then right) and if that neighboring column's value is different from "NAp" and "NAv" I want to report in the initial column either "ValueY" or "ValueX".
The tricky part is that I want to do it for multiple datasets (inside a loop) and the dataset don't always have the same number of columns.
However, the columns are named in a way that is easy to iterate over t1, t2, t3, etc.
Below is a reproducible example. Any help?
Fran <- data.frame (v1 = c("Fran", "Fran", "Fran"),
t1 = c("YES","NAv","NAv"),
t2 = c("NAp","YES","NAv"),
t3 = c("NAp","NAv","YES"),
t4 = c("NAp","NAv","YES")
)
Belg <- data.frame (v1 = c("Belg", "Belg", "Belg"),
t1 = c("YES","NAv","NAv"),
t2 = c("NAv","YES","NAv"),
t3 = c("NAp","NAv","YES")
)
ctr <- c("Belg", "Fran")
for (c in ctr) {
for (i in 1:4) {
t <- paste0("t", i)
h <- (i-1)
th <- paste0("t", h)
j <- (i+1)
tj <- paste0("t", j)
a <- get(c) %>%
mutate(across(starts_with(!!t), as.character)) %>%
mutate(!!th = ifelse(!!th == "NAv" & !!t != "NAv|NAp", "ValueY", !!th)) %>%
mutate(!!tj = ifelse(!!tj == "NAv" & !!t != "NAv|NAp", "ValueX", !!tj))
assign(c, a)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
