Q:

Picking a variable in R

I have two variables: X and state which are given below
set.seed(3)
state <- rbinom(15,4,0.6)
X <- c(1:15)
X
state

and the output is
> state
 [1] 3 2 3 3 2 2 4 3 2 2 2 2 2 2 1
> X
 [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15

I want to select the Xs corresponding to the same state. Any idea how to do this in R?

A:

Using split you get a list of 4 states
ll <- split(X,state)
$`1`
[1] 15

$`2`
[1]  2  5  6  9 10 11 12 13 14

$`3`
[1] 1 3 4 8

$`4`
[1] 7

ll[3]
$`3`
[1] 1 3 4 8

generally we use , ave to perform some operations while grouping.
For example here I get the mean of X by state:
ave(X,state,FUN = mean)
 [1]  4.000000  9.111111  4.000000  4.000000  9.111111  9.111111  7.000000  4.000000  9.111111  9.111111  9.111111  9.111111  9.111111  9.111111 15.000000

