[R] how to use a function in aggregate which accepts matrix and outputs matrix?
jim holtman
jholtman at gmail.com
Thu Apr 17 21:16:41 CEST 2008
Does something like this work for you? It is using 'lapply' with the
indices of the rows:
> x <- matrix(c( 'c1' , 'r6', '150', 'c1' , 'r4' ,'70' ,'c1' , 'r2' ,'20',
+ 'c1' , 'r5' ,'90', 'c2' ,'r2' ,'20', 'c3' , 'r1' ,'10'),
byrow=TRUE, ncol=3)
> # use lapply
> result <- lapply(split(seq(nrow(x)), x[,1]), function(.rows){
+ c(x[.rows[1],1], length(.rows), mean(as.numeric(x[.rows,3]))) #
return something
+ })
> result
$c1
[1] "c1" "4" "82.5"
$c2
[1] "c2" "1" "20"
$c3
[1] "c3" "1" "10"
> do.call(rbind, result)
[,1] [,2] [,3]
c1 "c1" "4" "82.5"
c2 "c2" "1" "20"
c3 "c3" "1" "10"
2008/4/17 zhihuali <lzhtom at hotmail.com>:
>
> Dear netters, suppose I have a matrix X [1,] 'c1' 'r6' '150'[2,] 'c1' 'r4' '70'[3,] 'c1' 'r2' '20'[4,] 'c1' 'r5' '90'[5,] 'c2' 'r2' '20'[6,] 'c3' 'r1' '10'I want to apply some funciton to groups of rows by the first column.If the function is just to calculate the average X[,3], it will be easy: aggregate(as.numeric(X[,3]),by=list(X[,1]),mean)But the function I want to use is more complicated. It will take as input a matrix(X[rows in the same group,c(2,3)], do some computation, and output another matrixwith the dimension (y,3), where y depends on the input. And I'd like the resultto be a rbind of each of the subset outputs. aggregate can not do that because the function is supposed to take vectors and output scalars.How can I apply the complicated function to groups of a matrix? Thanks! Zhihua Li
> _________________________________________________________________
> Windows Live Photo gallery 数码相机的超级伴侣,轻松管理和编辑照片,还能制作全景美图!
> http://get.live.cn/product/photo.html
> [[alternative HTML version deleted]]
>
>
> ______________________________________________
> 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.
>
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem you are trying to solve?
More information about the R-help
mailing list