R lapply statement with index

<>

This question already has an answer here:

Answers


The function mapply works like lapply but allows you to supply multiple vectors or lists.

In your case you can create a second vector, the same length of the list, just counting up:

mapply(myfunction, mylist, seq_along(mylist))

Let's try it:

myfunction<- function(values, index){ 
  cat("Adding values (", index, "): ", values[1], "...", values[2], " = ", sum(values), "\n" )
  invisible(values[1] + values[2])
}

mylist <- list(c(5, 4), c(3, 2), c(1, 3))

mapply(myfunction, mylist, seq_along(mylist))

Result:

Adding values ( 1 ):  5 ... 4  =  9 
Adding values ( 2 ):  3 ... 2  =  5 
Adding values ( 3 ):  1 ... 3  =  4 

Advanced user fun

Just for fun, a careful reading of the ?lapply manual page reveals that the following also works:

myfunction<- function(values){
    print(sprintf("Adding values: %i",substitute(values)[[3]]))
    return(values[1] + values[2])
}

lapply(mylist, myfunction)

Which suggests a general function adaptor could be created to supply index to your original function (or any other), modified to expect a second index argument:

myfunction<- function(values,index){
    print(sprintf("Adding values: %i",index))
    return(values[1] + values[2])
}

Now the adaptor

lapply_index_adaptor=function(f)function(x,...)f(x,substitute(x)[[3]],...)

and now the lapply call, with the adaptor:

lapply(mylist, lapply_index_adaptor(myfunction))

Need Your Help

How do you find out if a control is located on a tab control?

ms-access-2007 access-vba

Hopefully this should be fairly easy, although after much searching I cant figure this out.

How can I rewrite this flatten method without using class level variables?

ruby

I am working on building the flatten method in Ruby. Here is my code:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.