add column values based on other columns in data frame using for and if
You can use transform
:
transform(dse, dse1 = as.numeric(diag1 == 4230),
dse2 = as.numeric(diag2 == 4567))
No need to use a loop, just use ifelse
, for example
dse = within(dse, {
dse1 = ifelse(diag1 == 4230, 1, 0)
dse2 = ifelse(diag2 == 4567, 1, 0)
})
Don't use the if/else. Go vectorized as in:
dat$dse1 <- as.numeric(dat$diag1 == 4230)
dat$dse2 <- as.numeric(dat$diag2 == 4567)
Like this:
dse$dse1<-0
dse$dse2<-0
dse$dse1[dse$diag1==4230]<-1
dse$dse2[dse$diag2==4567]<-1
Please get yourself a good R tutorial (such as this) and read all about index vectors.