r - Applying sum / mean / etc. to a list -
in r why can apply mean / sum / etc. 1-d vector not 1-d list? how can perform such operations on list?
examples:
> myvector <- c(1,2,3,4) > myvector [1] 1 2 3 4 > sum(myvector) [1] 10 > mylist <- list(1,2,3,4) > mylist [[1]] [1] 1 [[2]] [1] 2 [[3]] [1] 3 [[4]] [1] 4 > sum(mylist) error in sum(mylist) : invalid 'type' (list) of argument
i think best option use unlist
reduce list vector, , call function. created following wrapper function this:
call_function_on_list = function(func, l) { func(unlist(l)) } l = c(1,2,3,4) call_function_on_list(mean, l) # [1] 2.5 call_function_on_list(sd, l) # [1] 1.290994 call_function_on_list(sum, l) # [1] 10
Comments
Post a Comment