sylvia
sylvia

Reputation: 217

Assign value to variables in a loop with some conditions in R

I would like to create a loop to

  1. create a serie of variables a1-a17 to a given dataframe (df)
  2. assign values of variable C to a1-a17 based on the value of variable b.

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

Answers (1)

s_baldur
s_baldur

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

Related Questions