[R] IF/Else

Gabor Grothendieck ggrothendieck at gmail.com
Fri Nov 11 01:00:32 CET 2005


Try using switch:

bioden <- Biomass /
  switch(paste(Gear),
    `20` = 141,
    `23` = 68,
    # ... fill in the ones I have omitted ...,
    `301` = DIST_TOW*4*1853)


On 11/10/05, Guenther, Cameron <Cameron.Guenther at myfwc.com> wrote:
> Hi,
> I am trying to write a for loop with if else statements to calculate
> biomass density estimates for different types of sampling gear.
> My code is:
>
> bmd=for (i in 1:length(Gear)){
> if (Gear==20) {bioden=Biomass/141}
> else {if (Gear==23) {bioden=Biomass/68}}
> else {if (Gear==160) {bioden=Biomass/4120}}
> else {if (Gear==170) {bioden=Biomass/2210}}
> else {if (Gear==300) {bioden=Biomass/(DIST_TOW*4*1853)}}
> else {if (Gear==301) {bioden=Biomass/(DIST_TOW*4*1853)}}
> }
>
> The syntax that is returned is:
>
> > bmd=for (i in 1:length(Gear)){
> + if (Gear==20) {bioden=Biomass/141}
> + else {if (Gear==23) {bioden=Biomass/68}}
> + else {if (Gear==160) {bioden=Biomass/4120}}
> Error: syntax error in:
> "else {if (Gear==23) {bioden=Biomass/68}}
> else"
> > else {if (Gear==170) {bioden=Biomass/2210}}
> Error: syntax error in "else"
> > else {if (Gear==300) {bioden=Biomass/(DIST_TOW*4*1853)}}
> Error: syntax error in "else"
> > else {if (Gear==301) {bioden=Biomass/(DIST_TOW*4*1853)}}
> Error: syntax error in "else"
> > }
> Error: syntax error in "}"
>
> It appears that the code works for the first two if/else statements and
> then fails there after.  Any suggestions?
>
> Cameron Guenther
> Associate Research Scientist
> FWC/FWRI, Marine Fisheries Research
> 100 8th Avenue S.E.
> St. Petersburg, FL 33701
> (727)896-8626 Ext. 4305
> cameron.guenther at myfwc.com
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html
>




More information about the R-help mailing list