Reputation: 217
I would like to create a loop to
I don't want to do this 17 times, please give me some advices to make them into a loop:
df$a1 <- ifelse(df$b ==1, df$c, NA )
df$a2 <- ifelse(df$b ==2, df$c, NA )
.
.
.
df$a16 <- ifelse(df$b ==16, df$c, NA )
df$a17 <- ifelse(df$b ==17 , df$c, NA )
thanks for any answers for a beginner!
Upvotes: 0
Views: 830
Reputation: 33488
Couldn't test this on real data since you didn't provide any reproducible example but a for loop might look like this:
for (i in 1:17) {
df[[paste0(a, i)]] <- ifelse(df$b == i, df$c, NA)
}
Or use lapply()
, which should be faster:
df[paste0(a, 1:17)] <- lapply(1:17, function(i) ifelse(df$b == i, df$c, NA))
Upvotes: 1