Reputation: 113
I'm plotting data and I have a loop that first finds all data corresponding to a particular ID number. Sometimes there is no data for that particular ID so I need to add a if else if statement within the loop because other wise I get an error that there is no x values for the plot
Actual Code
df<-subset(MonthFiltered,t_all<100)
IDunique<-unique(MonthFiltered$ID)
for (f in IDunique) {
temp<-subset(df,ID==f)
name<-paste(paste(f, "cdf", sep="-"),"png", sep=".")
png(name)
plot(ecdf(temp$t_all))
dev.off()
}
Need something like
for (f in IDunique) {
temp<-subset(df,ID==f)
#if temp obs.=0 then skip to next f
#else if
name<-paste(paste(f, "cdf", sep="-"),"png", sep=".")
png(name)
plot(ecdf(temp$t_all))
dev.off()
}
Upvotes: 1
Views: 2188
Reputation: 5066
Use NROW(temp$t_all[!is.na(temp$t_all)])
to get the length of temp$t_all
that contains valid data, as follows:
df <- subset(MonthFiltered,t_all<100)
# now loop through the unique values of ID
IDunique <- unique(MonthFiltered$ID)
for (f in IDunique) {
temp<-subset(df,ID==f)
# check to see if the subset actually contains non-na data
if (NROW(temp$t_all[!is.na(temp$t_all)]) > 0){
# there is valid data in the subset, so we can do something
name<-paste(paste(f, "cdf", sep="-"),"png", sep=".")
png(name)
plot(ecdf(temp$t_all))
dev.off()
} else {
# There is no data in the subset, so don't bother
}
}
N.B. it would have helped had you provided some realistic data and a better description of your data frame. I am guessing from your question that t_all
contains the data you wanted to look at.
Upvotes: 0
Reputation: 14366
If no observations then the number of rows of temp
will be 0, so you can skip to the next value.
if (nrow(temp) == 0) next
Upvotes: 3