Re: [R] Equivalent to a BY command in SAS

From: Rolf Turner <r.turner_at_auckland.ac.nz>
Date: Mon, 14 Apr 2008 16:17:58 +1200

On 14/04/2008, at 2:36 PM, zerfetzen wrote:

>
> Hi,
> I'm very new to R and absolutely love it. Does anyone know how to use
> something in R that functions like a BY command in SAS?
>
> For example, let's say you have a variable x, and you want to see
> the mean.
> Easy...
>
>> mean(x)
>
> But what if you want to see the mean of x conditional on another
> discrete
> variable? My best attempts so far are something like...
>
>> mean(x, y_cat=1)
>
> ...which of course doesn't work. I have downloaded plenty of R
> user guides
> that are very informative, but am not seeing much on detailed
> descriptives
> or data manipulation (for my life, I can't figure out how to sort an
> attached data frame, but that's another issue). Thanks.

 > set.seed(42)
 > x <- rnorm(100)
 > y <- sample(letters[1:3],100,TRUE)
 > by(x,y,mean)

INDICES: a
[1] 0.1089523

INDICES: b
[1] -0.2253035

INDICES: c
[1] 0.2997985

Or:

  > tapply(x,y,mean)

          a b c
  0.1089523 -0.2253035 0.2997985

                cheers,

                        Rolf Turner

######################################################################
Attention:\ This e-mail message is privileged and confid...{{dropped:9}}

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. Received on Mon 14 Apr 2008 - 04:21:56 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Mon 14 Apr 2008 - 10:30:29 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive