Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use a loop with mutate

Tags:

for-loop

r

dplyr

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?

like image 938
Mieke Avatar asked Aug 25 '26 16:08

Mieke


1 Answers

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
like image 121
ikop Avatar answered Aug 28 '26 07:08

ikop



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!