using apply() for non-arrays

6 views
Skip to first unread message

Asaf Weinstein

unread,
Feb 26, 2014, 1:36:22 AM2/26/14
to israel-r-user-group
Hi,

I have the following variables

row <- factor(rep(1:3,c(2,4,2))) 
col <- factor(rep(1:2,c(3,5))) 
y <- runif(8) 
cbind(row,col,y)

and I would like to apply the function "mean" to "y" by c("row","col"). I.e, I want to get the mean of y separately for each combination of "row" and "col".

Is converting to an array (and then using apply()) the easiest way?
If so, how do I create such an array?

Thanks a lot,
Asaf

amit gal

unread,
Feb 26, 2014, 1:53:20 AM2/26/14
to israel-r-...@googlegroups.com
tapply/aggregate will do the job

tapply(y,list(row,col),mean)

although it will return it in an array format, which you can later convert.
you can also use aggregate:

aggregate(y,list(row=row,col=col),mean)

which will return a data.frame with all possible col/row combinations, and their respective mean y value

hth
amit




--
You received this message because you are subscribed to the Google Groups "Israel R User Group" group.
To unsubscribe from this group and stop receiving emails from it, send an email to israel-r-user-g...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Jonathan Rosenblatt

unread,
Feb 26, 2014, 3:30:50 AM2/26/14
to israel-r-user-group
I would also look into the recent dplyr package:

It is certainly up to the job, with super fast c++ internals and a friendly interface.


--
Jonathan Rosenblatt
www.john-ros.com

Asaf Weinstein

unread,
Feb 26, 2014, 1:35:08 PM2/26/14
to israel-r-user-group
Toda raba Amit and Yonatan!

Asaf Weinstein

unread,
Feb 26, 2014, 2:50:15 PM2/26/14
to israel-r-user-group
Hi,
I have a another question.

row <- factor(rep(1:3,c(2,4,2))) 
col <- factor(rep(1:2,c(3,5))) 

How do I obtain a design matrix that includes a column for each of the variable levels, and no intercept (ie, each row is  a vector of indicators, one for each level of "row" and each level of "col")? 
model.matrix(~row+col-1) does not give what i'm looking for. I tried to look into the "contrasts" attributes but didn't see an option to get this 'saturated' model design matrix.

Thanks a lot again,
Asaf


Jonathan Rosenblatt

unread,
Feb 26, 2014, 3:01:29 PM2/26/14
to israel-r-user-group

Asaf Weinstein

unread,
Feb 26, 2014, 8:52:27 PM2/26/14
to israel-r-user-group
Thank you!
Reply all
Reply to author
Forward
0 new messages