Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

increment multiple arguments in lapply

Tags:

r

lapply

Is there a way to increment two arguments in an lapply function? For example

test <- function(pos,value){
   list[pos,value]
}

data=c(1,4,32,54) #not global
lapply(X=1:length(data),test, value=data[X])#this is the idea but the code doesnt work

The output would be list(list(1,1),list(2,4),list(3,32),list(4,54))

Another example would be

test <- function(pos,value,value2){
   list(pos,value,value2)
}

data=c(1,4,32,54) #not global
data2=c(2,6,3,21) #not global
lapply(X=1:length(data),test, value=data[X], value2=data2[X]) #this is the idea but the code doesn't work

The output would be list(list(1,1,2),list(2,4,2),list(3,32,6),list(4,54,21))

This may also help. I am pretty much trying to change the for loop into an lapply.

test <- function(pos,value,value2){
   list(pos,value,value2)
}

data=c(1,4,32,54) #not global
data2=c(2,6,3,21) #not global
for(i:length(data)){
  result=list(result,test(i,data[i],data2[i]))
}

Since the variables arent global I can't have the test function as

test <- function(pos){
   list(pos,data[pos],data2[pos])
}

I know that there is an easier way of writing this code to accomplish the same thing. But I am looking for a way to specifically increment two variables, or use the incremented value in an argument. The variables used in the examples, arent global, so I can't use them in the function and it needs to use the lapply function. In the codes, the lapply lines do not work, it was just the demonstrate the concept of what I am trying to do. Thank you.

Edit

So after learning about the mapply function. I realized that what I want is to create an lapply function that acts like an mapply

like image 581
Nikita Belooussov Avatar asked Mar 09 '26 14:03

Nikita Belooussov


1 Answers

I guess mapply is a better choice than lapply in you case.

Assuming you have a variable number of input arguments, you can rewrite test as

test <- function(pos,...){
  list(pos, ...)
}

For input in your example

data=c(1,4,32,54) #not global
data2=c(2,6,3,21) #not global

using mapply can get you there:

mapply(test, seq_along(data), data, data2, SIMPLIFY = F)
like image 101
ThomasIsCoding Avatar answered Mar 12 '26 04:03

ThomasIsCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!