Reputation: 776
Looking into the apply function family, sapply does not produce what I would like to. The problem I simplified to a basic example below. I create a vector and then perform a sum operation.
1.
v<-c(1:9)
sum(v)
#this returns 45 as expected
2.
sapply (v, sum)
#this returns [1] 1 2 3 4 5 6 7 8 9
How should I use sapply() to sum the vector above? Thanks a lot.
Upvotes: 0
Views: 387
Reputation: 210
you would use the reduce functional in this case
v<-c(1:9)
sum(v)
#this returns 45 as expected
purrr::reduce(v,sum)
#this also returns 45
# or base R
Reduce(sum,v)
# this also returns 45
Upvotes: 0
Reputation: 1369
If you must use sapply
, try,
sapply (list(v), sum)
[1] 45
The function sapply
applies the function sum
to each element. So for the vector v
, it was summing up each individual element.
It is clear the sum of one element, is that element.
Using the list
function, we them apply the sum
function to the first element of the list, which is v
, giving the desired result.
Just for understanding, we can use any function to move the vector "down a level", like data.frame
,
> sapply(data.frame(v), sum)[[1]]
[1] 45
But in your case, there is no need for sapply
.
Upvotes: 2
Reputation: 12155
sapply
applies a function to each element of a list. So what you're doing here is applying sum
to each number on its own – which doesn't accomplish anything. You can see what's happening in this example:
sapply(1:9, function(x) x + 1)
[1] 2 3 4 5 6 7 8 9 10
Using sum
with apply
only makes sense if you want to sum multiple elements of a list:
sapply(list(1:9, 3:4), sum)
[1] 45 7
Here, sum
is applied to each vector in the list
Upvotes: 3