3

I'm using the tapply function in order to get the count of variable over another variable. Here is the line of code: tapply(vip$VAR1,vip$VAR2,length)

However, I would like to filter only observations that have the value "1" on vip$VAR1, can I do this with tapply?

dat <- read.table(text = " VAR1 VAR2 admit       num
 0        0        0         7
 0        0        1         1
 0        1        0         3
 0        1        1         7
 1        0        0         5
 1        0        1         1
 1        1        0         0
 1        1        1         6", header = TRUE)
mql4beginner
  • 2,193
  • 5
  • 34
  • 73

1 Answers1

2

Would this do the trick?

tapply(dat[dat$VAR1==1,]$VAR1,dat[dat$VAR1==1,]$VAR2,length)

Or the simpler (from Ananda Mahto's comment):

with(dat[dat$VAR1 == 1, ], tapply(VAR1, VAR2, length))
Joe
  • 62,789
  • 6
  • 49
  • 67