This script works fine
F <- mutate(F, "1" = ifelse(dt == 1,1,0))
However, I'd like make a loop, because I want to apply it to 130 colums
I tried this, but it returns one extra column
for (i in 1:130) {
F <- mutate(F, "i" = ifelse(dt == i, 1, 0))
}
Can anybody help?
Instead of mutate you'll have to use mutate_ which is the "standard evaluation" version of mutate, which means that you can use quoted arguments. Here is the code:
## Sample data:
set.seed(1000)
F <- data.frame(dt = sample.int(5, 20, replace = TRUE))
## Your loop:
for (ii in 1:5){
F <- F %>% mutate_(.dots = setNames(list(paste0("ifelse(dt == ", ii, ",1,0)")), ii))
}
head(F)
# dt 1 2 3 4 5
# 1 2 0 1 0 0 0
# 2 4 0 0 0 1 0
# 3 1 1 0 0 0 0
# 4 4 0 0 0 1 0
# 5 3 0 0 1 0 0
# 6 1 1 0 0 0 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With