[R] try-error within for loop
Olga Lyashevska
olga at herenstraat.nl
Thu Aug 5 22:10:26 CEST 2010
Dear all,
I run a loop wrapped in try(), and for each of the rows where
"try-error" is true I want to fill that row with NA (at the moment it is
omitted). So I would expect to get a dataframe with 1000 rows some of
which would be empty, but instead I get a dataframe with 995 rows. In
this case missing 5 rows were omitted.
Any suggestions?
Thanks,
Olga
----------------
result<-list()
for(i in 1:1000)try({
hclass<-mydata2$tclass[mydata2$tspecies%in%com[[i]][[5]][[1]]]
horder<-mydata2$torder[mydata2$tspecies%in%com[[i]][[5]][[1]]]
hfamily<-mydata2$tfamily[mydata2$tspecies%in%com[[i]][[5]][[1]]]
hgenus<-mydata2$tgenus[mydata2$tspecies%in%com[[i]][[5]][[1]]]
hspecies<-mydata2$tspecies[mydata2$tspecies%in%com[[i]][[5]][[1]]]
hier<-cbind(hspecies,hgenus,hfamily,horder,hclass)
s<-nrow(hier)
s<-ifelse(s>1000,s/10,s)
taxa<-taxa2dist(hier[sample(s,replace=F),])
abd<-t(cbind(c(1:s),rep(1,s)))
taxdiv<-taxondiveO(abd,taxa)
if(class(result)=="try-error") result[[i]] <- NA
else result[[i]] <-taxdiv #it doesnt work
result[[i]]<-as.data.frame(result[[i]])[1,]},silent=T)
taxind<-do.call(rbind,result)
taxind[1:5,]
number D Dstar Lambda Dplus SDplus
1 589 94.72456 94.93875 142.4468 94.88140 55885.15
2 428 80.38656 80.63660 328.7728 80.90432 34627.05
3 282 88.03613 88.45139 332.8963 88.53554 24967.02
4 1320 80.43822 80.51943 328.1416 80.63355 106436.29
5 1077 80.43121 80.53073 287.2267 80.62954 86838.01
and instead I want to see NA where appropriate
taxind[1:5,]
number D Dstar Lambda Dplus SDplus
1 589 94.72456 94.93875 142.4468 94.88140 55885.15
2 428 80.38656 80.63660 328.7728 80.90432 34627.05
3 282 88.03613 88.45139 332.8963 88.53554 24967.02
4 NA NA NA NA NA NA
5 1077 80.43121 80.53073 287.2267 80.62954 86838.01
More information about the R-help
mailing list