[R] lapply with mahalanobis function

Dimitris Rizopoulos dimitris.rizopoulos at med.kuleuven.be
Wed Apr 5 11:26:06 CEST 2006


you could use mapply(), e.g.,

mapply(mahalanobis, center = centroids, cov = cov.mat, MoreArgs = 
list(x = test))


I hope it helps.

Best,
Dimitris

----
Dimitris Rizopoulos
Ph.D. Student
Biostatistical Centre
School of Public Health
Catholic University of Leuven

Address: Kapucijnenvoer 35, Leuven, Belgium
Tel: +32/(0)16/336899
Fax: +32/(0)16/337015
Web: http://www.med.kuleuven.be/biostat/
     http://www.student.kuleuven.be/~m0390867/dimitris.htm


----- Original Message ----- 
From: "Mike White" <mikewhite.diu at btconnect.com>
To: <R-help at stat.math.ethz.ch>
Sent: Wednesday, April 05, 2006 10:58 AM
Subject: [R] lapply with mahalanobis function


> Hi
> I am trying to use lapply with a function that requires two list 
> type
> variables but I cannot find a way to program it and could not find 
> any hints
> under lapply or searching the R-list.  As an example I have used the
> mahalanobis function with the iris data. Is there a way to replace 
> the for
> loop with the lapply function or similar?
>
> data(iris)
> set.seed(0)
> sa<-sample(nrow(iris),2)
> train<-iris[!(1:nrow(iris) %in% sa),]
> test<-iris[sa,1:4]
> Sp.data<-split(train[,1:4], train[,"Species"])
>
> cov.mat<-lapply(Sp.data, cov)
> centroids<-lapply(Sp.data, function(x) apply(x,2,mean))
>
> ## can the for loop be replaced by an lapply function?
> result<-list()
> for (i in 1:length(Sp.data)){
> result[[i]]<-mahalanobis(test, center=centroids[[i]], 
> cov=cov.mat[[i]])
> }
>
> result
> [[1]]
>        135          40
> 620.9687898   0.6085936
>
> [[2]]
>      135        40
> 27.61433 104.97892
>
> [[3]]
>      135        40
> 10.96607 167.81203
>
> Thanks
> Mike White
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 


Disclaimer: http://www.kuleuven.be/cwis/email_disclaimer.htm




More information about the R-help mailing list