sapply()和未使用的函数参数

时间:2017-12-11 00:33:01

标签: r sapply

我是R的新手,并试图解决其中一个功课问题。我正在练习使用的一系列功能是apply()系列。具体来说,这个问题要求使用sapply()函数来计算向量的平均值。

稍微设置背景。首先,这是我的prop_peer_pressure函数:

写一个函数道具同伴压力,该压力包含医生和一个月的索引号,并返回已经按该月开出四环素的医生联系人的比例。如果医生没有接触者,您的功能应该返回NaN。检查医生37,第5个月返回0.6的比例。

prop_peer_pressure <- function(index, month) {
   if (doc.contacts[index] == 0) {
     return(NaN)
   }
   else {
   return(count_peer_pressure(index, month) / doc.contacts[index])
 }
}


prop_peer_pressure(37, 5)
# 37 
# 0.6 

adopters()是我写的另一个函数,它返回在月x开始开处方的医生的索引。

adopters(2)
# [1]  10  13  20  56  71  75  76  87 107


sapply(adopters(2), prop_peer_pressure, 2)
# 10     13     20     94     128    132    133    168    200
# 0.0000 0.3333 0.1428 0.0909 0.3333 0.4000 0.3333 0.1666 0.3333

这有效,但我想知道R如何知道哪个&#34;索引&#34;它需要输入&#34; prop_peer_pressure&#34;功能?由于我的prop_peer_pressure函数接受2个参数(索引,月份)......

sapply(adopters(2), prop_peer_pressure, index = adopters(2), month = 2)
  

FUN中的错误(X [[i]],...):未使用的参数(X [[i]])

1 个答案:

答案 0 :(得分:3)

如何运作

关于sapply如何工作,这三个都给出了相同的结果:

f <- function(x, y) x + y

sapply(1:5, f, 10)
## [1] 11 12 13 14 15

sapply(1:5, function(x) f(x, 10))
## [1] 11 12 13 14 15

c(f(1, 10), f(2, 10), ..., f(5, 10))
## [1] 11 12 13 14 15

在每种情况下,对于每个1:5的元素,f运行一次,使用该元素作为f的第一个参数,并使用10作为f的第二个参数。

最后一个问题的错误

问题中的最后一个问题是错误,因为它试图将三个参数传递给函数,但该函数只接受两个参数。 prop_peer_pressure的第一个参数来自sapply的第一个参数的连续组件,而prop_peer_pressure的其余两个参数是index =和month =,它们是在对sapply的调用结束时指定的。那是它试图运行这个:

c(prop_peer_pressure(10, index = adopters(2), month = 2), 
  prop_peer_pressure(13, index = adopters(2), month = 2), 
  ... etc ...)

这显然不是意图。