4

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?

Mieke
  • 41
  • 1
  • 1
  • 2
  • 2
    could you perhaps add a [reproducible example?](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – Vandenman May 23 '17 at 22:06
  • To apply the 'ifelse()' to each column you could use a functional base R e.g. sapply () and avoid the loop. – Edgar Santos May 23 '17 at 22:13
  • 3
    You should check out `?mutate_each` and/or `?mutate_all` – Ian Wesley May 23 '17 at 22:31
  • As @IanWesley suggested, using `mutate_all` would be a very easy way to get around that. If you have other columns that you don't want to have it applied to, just select them out prior to the `mutate_all` call. – Phil May 24 '17 at 05:06

2 Answers2

2

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
ikop
  • 1,760
  • 1
  • 12
  • 24
  • 1
    I tried to use this but I got the following error: Error in col_name - past_col_name : non-numeric argument to binary operator In addition: Warning message: `mutate_()` was deprecated in dplyr 0.7.0. Please use `mutate()` instead. See vignette('programming') for more help I am exactly trying to refer to coluymn names with quotes "col 1" – lu-202 Apr 12 '22 at 10:30
0

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)
}
sairaamv
  • 86
  • 4