[R] Subset command and the : operator

Chris Beeley chris.beeley at gmail.com
Fri May 27 13:10:36 CEST 2011


Hello-

I have some code that looks like this:

with(mydatalocal, sum(table(Service[Time==5:8])))

This is designed to add up the numbers of responses between the Time
codes 5 to 8 (which are integers and refer to quarters). Service is
just one of the variables, I'm just trying to count the number of
responses so I picked any of the variables. However, there is
something wrong, it returns far too low a number for the number of
responses. Indeed, if I run this:

with(mydatalocal, sum(table(Service[Time==5|Time==6|Time==7|Time==8])))

I get 4 times as many responses.

I've tried to recreate the problem with the following code:

mydata=data.frame(matrix(c(rep(1, 10), rep(2, 10), rep(3, 10), seq(1,
10, 1), seq(11, 20, 1), seq(21, 30, 1)), ncol=2))

with(mydata, sum(table(X1[X2==9:12])))

with(mydata, sum(table(X1[X2==9|X2==10|X2==11|X2==12])))

but to my immense frustration it actually seems to work fine there,
the same number, 4, both times. However, it does generate the
following error message:

In X2 == 9:12 :
  longer object length is not a multiple of shorter object length

I know I can use X1[ Time < 9 & Time > 3] but I would like to know
what is wrong with the 5:8 usage in case I put it somewhere else and
don't notice the problem.

Many thanks!

Chris Beeley
Institute of Mental Health



More information about the R-help mailing list