[R] apply a function on elements of a list two by two
Patrick Hausmann
patrick.hausmann at uni-bremen.de
Sat May 8 16:12:44 CEST 2010
Am 08.05.2010 15:43, schrieb Joris Meys:
> Dear all,
>
> I want to apply a function to list elements, two by two. I hoped that combn
> would help me out, but I can't get it to work. A nested for-loop works, but
> seems highly inefficient when you have large lists. Is there a more
> efficient way of approaching this?
>
> # Make some toy data
> data(iris)
> test<- vector("list",3)
> for (i in 1:3){
> x<- levels(iris$Species)[i]
> tmp<- dist(iris[iris$Species==x,-5])
> test[[i]]<- tmp
> }
> names(test)<- levels(iris$Species)
# Using 'lapply' and 'split' is a little bit more flexible:
test <- lapply(split(iris[, -5], iris$Species), function(x) dist(x))
>
> # nested for loop works
> for(i in 1:2){
> for(j in (i+1):3){
> print(all.equal(test[[i]],test[[j]]))
> }
> }
>
> # combn doesn't work
> combn(test,2,all.equal)
Sorry, no answer
HTH
Patrick
>
> Cheers
> Joris
More information about the R-help
mailing list