[R] lapply with mahalanobis function
Mike White
mikewhite.diu at btconnect.com
Wed Apr 5 10:58:20 CEST 2006
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
More information about the R-help
mailing list