0

I have a R dataframe df as given below:

ID        End_week
2500076   1223
6801102   1325
6801282   1308
6803252   1426
9882106   1426
9894112   1217

I want to insert a new column status with 0/1 values - 1 if End_week equals 1426 and 0 otherwise. Final output should look like this:

ID        End_week   Status
2500076   1223       0
6801102   1325       0
6801282   1308       0
6803252   1426       1
9882106   1426       1
9894112   1217       0

I wrote a while loop as given below:

while(i<=length(df$End_week)) {
  if(df$End_week[i]==1426) {
    status[i] <- 1
  } else {
    status[i] <- 0
  }
  i=i+1
}

But, I get the following error:

Error in if (df$End_week[i] == 1426) { : 
  argument is of length zero

I know that the question has been asked before and so I referred these answers, but didn't find them helpful in my scenario. I checked for any NA values in End_week column and there aren't any. Can someone suggest a way out?

Rnovice
  • 333
  • 1
  • 5
  • 18
  • 2
    `df$Status <- ifelse(End_week == 1426, 1, 0)` or `df$Status <- ifelse(End_week == '1426', 1, 0)` depending on class of df$Status – CPak May 23 '18 at 19:06
  • 1
    Or just convert the logical vector to `integer` i.e. `as.integer(End_week == 1426)` – akrun May 23 '18 at 19:10
  • @CPak - that's so cool. I didn't know this trick. And it works for me! Thanks. – Rnovice May 23 '18 at 19:13

1 Answers1

1

I'd suggest researching dataframe subsetting as your missing out on a substantial benefit of r.

df$Status <- 0
df$Status[df$End_week == 1426] <- 1
icj
  • 719
  • 6
  • 12