1

I am trying to speed my code by using lapply instead of for loop to provide functions variables in the lapply function I provide all functions variables in lapply function. but it gives me this error, what is the problem in here ?

Error in functionE(A[[i]],A,weight) : 
argument "weight" is missing, with no default

code structure :

weight<-weight
A<-functionB() #A is a list 
C<-lapply(1:length(A),function(i,A,weight){

if(functionE(A[[i]],A,weight)==TRUE)
    #some other functions
return(A)
    })

EDIT :actually A is list of graphs (for the simplicity , I lay out like that)

 for (i in 1:vcount(A[[1]])
    {
     #some function and if condition that needs((weight and, A))
     #there is a function which return j
      V(A[[1]])[i]$attribute2<-V(A[[1]])[j]$attribute1
     }

so I want to access Awhich changes in the for.

academic.user
  • 639
  • 2
  • 9
  • 28

1 Answers1

1

First of all in R variables in the global environment are visible to functions, so you don't have to pass them the way you do.

I am not entirely clear what you want to do but apply family of functions use your input as the first variable and other variables need to be constant (unless you are using mapply). You need to pass these other variables as variables in (s/l)apply.

lappy(1:length(A), function(i,A,weight){
    #whatever your function does
},A,weight)

in this case i will be alternating from 1 to length(A) while all other variables would remain whatever they were. Keep in mind that you don't really need to add A and weight at all since you can use them inside the function without passing them manually.

OganM
  • 2,543
  • 16
  • 33
  • thanks for your answer.for every element of the list `(length(A))` I want to do some operation on, these functions need `A `, `weight `and `i ` to specify which element we want to calculate for. as i serached this [link](http://stackoverflow.com/questions/2656792/can-lapply-not-modify-variables-in-a-higher-scope) said we can not alter things outside the scope of an apply function, – academic.user May 07 '15 at 23:01
  • what if `A ` changes in the function consider `A `as list of list and some element will changes in the function. – academic.user May 07 '15 at 23:03
  • actually you can alter things outside a function with the `<<-` operator. for instance `a=1;b=1;lapply(a,function(x){b<<-x+5})` would make `b=6` outside lapply as well. you might want to write how would you do it using a `for` since I am still not exactly clear about your purpose – OganM May 07 '15 at 23:34
  • @OganM I'm not sure why the double ´<<´ . One is also fine. – tagoma Feb 25 '18 at 12:59