Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R lapply different function to each element of list

Tags:

function

r

lapply

I have a list (in R) where the elements are different data types, e.g., the first element is numeric and the second element is character. I would like to apply a different function to each element. For example, in the code below I try to apply the sum function only to the first element and the length function only to the second element. Is there a way to apply a different function to each element of a list (without breaking up the list)?

data <- list(
  A = rnorm(10),
  B = letters[1:10]
)

lapply(data, list(sum, length))

mapply(function(x) sum, length, data)
like image 380
user1491868 Avatar asked Jul 06 '15 18:07

user1491868


People also ask

How do you apply a function to each element of a list in R?

lapply() function in R Programming Language is used to apply a function over a list of elements. lapply() function is used with a list and performs the following operations: lapply(List, length): Returns the length of objects present in the list, List.

How do I apply multiple functions to a list in R?

The lapply () and sapply () functions can be used for performing multiple functions on a list in R. This function is used in order to avoid the usage of loops in R. The difference between both the functions is the sapply () function does the same job as lapply () function but returns a vector.

What does the Lapply () function in R is used for?

The lapply() function helps us in applying functions on list objects and returns a list object of the same length. The lapply() function in the R Language takes a list, vector, or data frame as input and gives output in the form of a list object.

Which function is same as Lapply () in R?

sapply() function It is useful for operations on list objects and returns a list object of same length of original set. Sapply function in R does the same job as lapply() function but returns a vector.


2 Answers

How about

mapply(function(a,b) b(a), data, list(sum, length))

Notice that we put the functions in mapply in a list as well.

like image 72
MrFlick Avatar answered Sep 23 '22 01:09

MrFlick


I would do something like

sapply( data, function(x) (if(is.character(x)) length else sum)(x) )

Complicated alternatives. If speed is a concern, vapply should be faster:

vapply( data, function(x) (if(is.character(x)) length else sum)(x), numeric(1) )

If you need to use length many times, it's fast to use lengths (available in R 3.2.0+):

res          <- lengths(data)
get_sum      <- !sapply(data,is.character)
res[get_sum] <- sapply(data[get_sum],sum)
like image 40
Frank Avatar answered Sep 22 '22 01:09

Frank