Mieke
Mieke

Reputation: 41

use a loop with mutate

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?

Upvotes: 4

Views: 30126

Answers (2)

ikop
ikop

Reputation: 1790

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

Upvotes: 2

sairaamv
sairaamv

Reputation: 86

Instead of mutate, you can assign new columns in loop

x <- runif(100, 0, 1)
y <- runif(100, 0, 1)
class <- round(runif(100, 0, 1))
df <- data.frame(cbind(x, y, class))

df <- mutate(df, "1" = ifelse(x == 1,1,0))

for(i in 1:130){
  print(i)
  cola <- paste('col', i, sep= '')
  df[[cola]] <- ifelse(x == i, 1, 0)
}

Upvotes: 0

Related Questions