User981636
User981636

Reputation: 3621

R Iterative substitution with for loop and if else

I'm a new useR so please bear with me.

I have a data frame, dfalpha, with several variables and its corresponding values. Something similart to:

individual  variable    value
alpha   a   0.2
alpha   b   0.4
alpha   c   0.6
alpha   d   0.8

I have another data frame dfbeta, for other individual

individual  variable    value
beta    a   0.1
beta    b   0.8
beta    c   0.5
beta    d   0.3

I need to substitute alpha a value (0.2) for beta a value (0.1), then undo this substitution and substitute alpha b value (0.4) for beta b value (0.8). And so on for the rest.

I have tried:

for(i in 1:4){
  if (i = 1) {
    dfalpha$value[i] <- dfbeta$value[i] 
  } else {
    dfalpha$value[i] <- dfbeta$value[i]
    dfalpha$value[i-1] <- dfalphapermanent[i-1]
  } 
  print(dfalpha) 
}

I have a dfalphapermant data frame out of the loop for undoing the substitution. In order to check everything is OK, I print the results. I have been trying but it seems it doesn't work. I have checked the if and else statement but they seem to be correctly positioned.

PS: Sorry for the patchy style of programming, I am very new and self taught on this.

Upvotes: 0

Views: 233

Answers (1)

Se&#241;or O
Se&#241;or O

Reputation: 17412

The problem is you have the statement if (i = 1). i=1 always evaluates to TRUE because it's assigning 1 to i.

You want if (i == 1)

Upvotes: 1

Related Questions