当我查看R Packages的来源时,我看到了sweep经常使用的函数。有时候,当一个简单的函数就足够了(例如apply)时,就会用到它,而在其他时间,如果不花费大量的时间来遍历其中的代码块,就不可能确切知道它在做什么。
我可以sweep使用更简单的功能来重现效果,这一事实表明我不了解sweep的核心用例,而经常使用此功能的事实表明它非常有用。
上下文:
sweep是R标准库中的函数;它的参数是:
sweep(x, MARGIN, STATS, FUN="-", check.margin=T, ...)
# x is the data
# STATS refers to the summary statistics which you wish to 'sweep out'
# FUN is the function used to carry out the sweep, "-" is the default
如您所见,参数与相似,apply尽管还sweep需要一个参数STATS。
另一个关键区别是,sweep返回的数组与输入数组的形状相同,而返回的结果apply取决于传入的函数。
sweep 实际上:
# e.g., use 'sweep' to express a given matrix in terms of distance from
# the respective column mean
# create some data:
M = matrix( 1:12, ncol=3)
# calculate column-wise mean for M
dx = colMeans(M)
# now 'sweep' that summary statistic from M
sweep(M, 2, dx, FUN="-")
[,1] [,2] [,3]
[1,] -1.5 -1.5 -1.5
[2,] -0.5 -0.5 -0.5
[3,] 0.5 0.5 0.5
[4,] 1.5 1.5 1.5
因此,总而言之,我正在寻找的是一个或两个示例用例sweep。
请不要背诵或链接到R文档,邮件列表或任何“主要” R资源-假设我已阅读它们。我感兴趣的是经验丰富的R程序员/分析师如何sweep在自己的代码中使用。
apply我可以得出此结果的唯一用法是类似的东西t(apply(t(M), 2, "-", dx)),但这很讨厌。