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)
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.
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With