[R] Passing arguments between apply and l(s)apply functions vs. nested for loop
Charles Berry
ccberry at ucsd.edu
Thu Mar 28 04:55:23 CET 2013
Mark Orr <mo2259 <at> columbia.edu> writes:
>
> Hi R community,
> I have a question concerning passing arguments between apply and lapply?
[snip]
>
> #START CODE SNIPPET
>
> #LIST AND VECTOR
> rm(list=ls())
> l <- list(1:3,2:3,4:10,7:9)
> v <- 1:3
>
> #USED IN j loop to catch values
> catch.mat <- matrix(NA,nrow=length(v),ncol=length(l))
>
> #LOOPS
> for (i in 1:length(v)){
> for (j in 1:length(l)) {
> catch.mat[i,j] <- sum(l[[j]]==i)
> }
> }
>
> #SIMPLY APPLY OVER catch.mat
> catch.all <- apply(catch.mat,1,sum)
>
> catch.mat
> catch.all
>
Given the constraint you state about uniqueness,
> table(factor(unlist(l),v))
1 2 3
1 2 2
gives the same answer as catch.all --- up to names which you can
remove with unname(table(factor(unlist(l),v)))
[deleted]
>
> #THEN I ADD A NEW FUNCTION
> f.2 <- function(x,l=l){
> i <- x
> rm(x)
> return(sum(lapply(l,function(x) sum(x==i))))
> }
>
> mat.1 <- matrix(1:2318,nrow=1,ncol=2318)
> apply(mat.1,1,f.2)
>
> #BUT GET ERROR
> #> apply(mat.1,1,f.2)
> #Error in lapply(l, function(x) sum(x == i)) :
> # promise already under evaluation: recursive default argument reference or
earlier problems?
Always helps to ponder the error message --- 'recursive default argument'.
Here is an example:
foo <- function(x=x) x
> foo() ## here it comes again!
Error in foo() :
promise already under evaluation: recursive default argument reference
or earlier problems?
> foo(1) # this works
[1] 1
>
The default is what you use when the argument is not given in the call.
And x=x confuses the evaluator.
You can avoid confusion by choosing a different name like this:
> foo <- function(xx=x) xx
> x <- 3
> foo()
[1] 3
>
[rest deleted]
HTH,
More information about the R-help
mailing list