[英]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. 在应用功能家族中,sapply无法产生我想要的结果。 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? 我应该如何使用sapply()对上述向量求和? Thanks a lot.
非常感谢。
sapply
applies a function to each element of a list. sapply
将函数应用于列表的每个元素。 So what you're doing here is applying sum
to each number on its own – which doesn't accomplish anything. 因此,您在这里所做的就是将
sum
应用于每个数字-这并没有完成任何事情。 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: 仅当您想对列表的多个元素
sum
,才将sum
和apply
一起apply
才有意义:
sapply(list(1:9, 3:4), sum)
[1] 45 7
Here, sum
is applied to each vector in the list 这里,
sum
应用于列表中的每个向量
If you must use sapply
, try, 如果您必须使用
sapply
,请尝试,
sapply (list(v), sum)
[1] 45
The function sapply
applies the function sum
to each element. 功能
sapply
应用功能sum
到每个元素。 So for the vector v
, it was summing up each individual element. 因此对于向量
v
,它是对每个单独的元素求和。
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. 我们使用
list
函数,将sum
函数应用于列表的第一个元素v
,得到所需的结果。
Just for understanding, we can use any function to move the vector "down a level", like data.frame
, 为了理解,我们可以使用任何函数将向量“下移”,例如
data.frame
,
> sapply(data.frame(v), sum)[[1]]
[1] 45
But in your case, there is no need for sapply
. 但就您而言,不需要
sapply
。
you would use the reduce functional in this case 在这种情况下,您将使用reduce功能
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.