[R] Function for subset of cases/lines

Matthias Kohl Matthias.Kohl at stamats.de
Thu May 15 10:28:04 CEST 2008


Dear Stefan,

what about

q1<-c(4660,5621,5629,8030,8080,8180,8501,8190,8370,8200)
x <- data.frame(number = c(4660, 5010, 5621, 5629, 8030, 8080 , 8090, 
8180, 8501, 8190, 8200, 8370, 8200), height = c(2.5, 1.4, 0.8, 2.3, 2.5, 
2.4, 0.9, 1.4, 1.2, 1.9, 2.0, 2.1, 1.8))

ind <- x[,"number"] %in% q1
mean(x[ind,"height"])

## or shorter
mean(x[x[,"number"] %in% q1,"height"])

Best,
Matthias

Stefan Uhmann wrote:
> Hi,
>
> I have a vector:
>
> q1<-c(4660,5621,5629,8030,8080,8180,8501,8190,8370,8200)
>
> The following command gives me the mean of its elements:
>
> mean(q1)
> [1] 7346.1
>
> What can I do to do the same for the variable 'height', but only for 
> the cases/rows which have one of the elements of q1 as 'number':
>
>   number height
> 1 4660    2.5
> 2 5010    1.4
> 3 5621    0.8
> 4 5629    2.3
> 5 8030    2.5
> 6 8080    2.4
> 7 8090    0.9
> 8 8180    1.4
> 9 8501    1.2
> 10 8190    1.9
> 11 8200    2.0
> 12 8370    2.1
> 13 8200    1.8
>
> Thanks for any help,
> Stefan
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Dr. Matthias Kohl
www.stamats.de



More information about the R-help mailing list