简体   繁体   中英

R, sapply does not seem to apply the function provided

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.

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM