nee
nee

Reputation: 125

for loop and applying condition to ignore limited data

I have a data.frame in this format

     data.frame':   566171 obs. of  10 variables:
     $ id    : Factor w/ 120 levels "2200100","2200200",..: 1 1 1 1 1 1 1 1 1 1 ...
     $ year  : int  1950 1950 1950 1950 1950 1950 1950 1950 1950 1950 ...
     $ yday  : int  1 2 3 4 5 6 7 8 9 10 ...
     $ date  : Date, format: "1950-01-01" "1950-01-02" ...
     $ t_max : atomic  -17.2 -23.9 -25 -22.8 -19.4 -19.4 -11.1 -15.6 -17.8 -20.6 ...
     ..- attr(*, "long.name")= chr "daily maximum temperature"
     ..- attr(*, "units")= chr "°C"
      $ rain  : atomic  0 0 0 0 0 0 0 0 0 0 ...
     ..- attr(*, "long.name")= chr "total rainfall"
      ..- attr(*, "units")= chr "mm"

I wrote the following loop to subset the data:

    library (seas)

    uniq <- unique(unlist(mdata$id))
    for (i in 1: length(uniq)){
      data_1 <- subset(mdata, id == uniq[i])
      d1 <-mksub(data_1) 
      year.plot(mksub(d1))
    }

It works well to a point, however, the loop stops running when station id do not have sufficient data. How can I tell R within my loop to ignore station id that do not have sufficient data to apply year.plot function and continue with other station until the final id?

Upvotes: 1

Views: 103

Answers (1)

bstockton
bstockton

Reputation: 577

Looks like Thomas laid out what you should be doing in general. Let me see if I can put that together for you. I am going to use mscdata from the seas package, and assume that anything less than 2 is insufficient

library(seas)

data(mscdata)

uniq <- unique(unlist(mscdata$id))


for (i in 1: length(uniq)){
  data_1 <- subset(mscdata, id == uniq[i])
  try(if(length(data_1) < 2) {
    next
  } else {
    d1 <-mksub(data_1) 
    year.plot(mksub(d1))
  })
}

This reproducible example should work for you.

Upvotes: 1

Related Questions