[R] Assignments inside lapply

ONKELINX, Thierry Thierry.ONKELINX at inbo.be
Wed Apr 27 12:06:07 CEST 2011


Dear Alex,

I think you want to use apply()

ij <- expand.grid(i = seq_len(dimx),j = seq_len(dimy))
Powermap <- apply(ij, 1, function(x){
	Pr(x, c(PRX, PRY), f)
})

Best regards,

Thierry

----------------------------------------------------------------------------
ir. Thierry Onkelinx
Instituut voor natuur- en bosonderzoek
team Biometrie & Kwaliteitszorg
Gaverstraat 4
9500 Geraardsbergen
Belgium

Research Institute for Nature and Forest
team Biometrics & Quality Assurance
Gaverstraat 4
9500 Geraardsbergen
Belgium

tel. + 32 54/436 185
Thierry.Onkelinx op inbo.be
www.inbo.be

To call in the statistician after the experiment is done may be no more than asking him to perform a post-mortem examination: he may be able to say what the experiment died of.
~ Sir Ronald Aylmer Fisher

The plural of anecdote is not data.
~ Roger Brinner

The combination of some data and an aching desire for an answer does not ensure that a reasonable answer can be extracted from a given body of data.
~ John Tukey
  

> -----Oorspronkelijk bericht-----
> Van: r-help-bounces op r-project.org 
> [mailto:r-help-bounces op r-project.org] Namens Alaios
> Verzonden: woensdag 27 april 2011 11:37
> Aan: R-help op r-project.org
> Onderwerp: [R] Assignments inside lapply
> 
> Dear all I would like to ask you if an assignment can be done 
> inside a lapply statement.
> 
> For example
> 
> I would like to covert a double nested for loop
> 
> for (i in c(1:dimx)){
>   for (j in c(1:dimy)){
>       Powermap[i,j] <- Pr(c(i,j),c(PRX,PRY),f)
>    }
> }
> 
> to something like that:
> 
> 
> ij<-expand.grid(i=seq(1:dimx),j=(1:dimy))
> 
> unlist(lapply(1:nrow(ij),function(rowId) { return 
> (Powermap[i,j]<-Pr(c(ij$i[rowId],ij$j[rowId]),c(PRX,PRY),f))   }))
> 
> 
> as you can see lapply does not return nothing as the 
> assignment is done inside the function. Would that work 
> correctly? What are the cases such a statement will misfunction?
> 
> I would like to thank you in advace for your help.
> 
> Best Regards
> Alex
> 
> ______________________________________________
> R-help op 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.
> 


More information about the R-help mailing list