[R] apply a function separately on each element of a list

jeff6868 geoffrey_klein at etu.u-bourgogne.fr
Tue Aug 28 10:33:43 CEST 2012


Yes, this is it (as would say michael)! Thank you guys!

Last question about another function on this list: imagine this list is my
data after your function for the regression model:

mydf <- data.frame(x=c(1:5), y=c(21:25),z=rnorm(1:5))
mylist <- rep(list(mydf),5) 

Don't care about this fake data, it's just for the example. I've my results
in column "z" (from regression) for each DF of the list, and 2 other columns
"x" and "y" representing some spatial coordinates.

I have another independent DF containing a list of "x" and "y" too,
representing some specific regions (imagine 10 regions):
region <- data.frame(x=c(1:10),y=c(21:30),region=c(1:10))
 
The final aim is to have for each 10 regions, a value "z" (of my regresion)
from the nearest point of each of the DF of my list.
That means for one region: 10 results "z" from DF1 of my list, then 10 other
results "z" from DF2, ...

I already have a small function to look for the nearest value:

min.dist <- function(p, coord){
     which.min( colSums((t(coord) - p)^2) )
}

Then, I'm trying to make a loop to havewhat I want, but I have difficulties
with the list. I would need to put 2 variables in the loop, but it doesn't
works.

This works approximately if I just take 1 DF of my list:

for (j in 1:nrow(region))
	{
	 	
imin[j] <- min.dist(c(plante[j,1],plante[j,2]),mylist[[j]][,1:2])
final[j] <- mylist[[j]][imin[j], "z"]
final <- as.data.frame(final)
}

But if I select my whole list (in order to have one column of results for
each DF of the list in the object "final"), I have errors.

I think the first problem is that the length of "regions" is different of
the length of my list, and the second maybe is about adding a second
variable for the length of my list.

Is there any solution?




--
View this message in context: http://r.789695.n4.nabble.com/apply-a-function-separately-on-each-element-of-a-list-tp4641186p4641530.html
Sent from the R help mailing list archive at Nabble.com.




More information about the R-help mailing list