Skip to content
Prev 333398 / 398506 Next

if else in R

Hi,
On Nov 19, 2013, at 9:41 PM, Nick Matzke <matzke at berkeley.edu> wrote:

            
As a follow up, you could make a logical index for the condition as Nick suggests.

a<-c(1,2,3,4)
b<-c(2,0,5,0)
ab<-data.frame(a,b)
ix <- ab[,'b'] > 0
ix
# [1]  TRUE FALSE  TRUE FALSE

ab[ix,'c'] <- ab[ix,'a']/ab[ix,'b']
ab[!ix,'c'] <- 0
ab
#  a b   c
# 1 1 2 0.5
# 2 2 0 0.0
# 3 3 5 0.6
# 4 4 0 0.0

I'm not a big fan of the ab$b form of subsetting, I find ab[,'b'] more readable for my fading eyesight.  But you could do it your way, too.

ab$c[ix] <- ab$a[ix]/ab$b[ix]

Cheers,
Ben
Ben Tupper
Bigelow Laboratory for Ocean Sciences
60 Bigelow Drive, P.O. Box 380
East Boothbay, Maine 04544
http://www.bigelow.org