Reputation: 326
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)
Upvotes: 10
Views: 2221
Reputation: 66819
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)
Upvotes: 6
Reputation: 206232
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.
Upvotes: 17