简体   繁体   中英

Error in if condition {: argument is of length zero

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM