我正在刷我的R技能,最后觉得我已经掌握了奇怪的扫描功能,例如
df <- data.frame(a = 1:3, b = 2:4)
sweep(df, MARGIN = 2, STATS = c(5, 10), FUN = "*")
## a b
## 1 5 20
## 2 10 30
## 3 15 40
Run Code Online (Sandbox Code Playgroud)
并且更有效地在这里,在教程中,我正在实施中R的空间相互作用模型
他们说你明白的一个标志就是你可以用很多方式说出来,而且我认为这在编程中的应用比其他任何地方都要多.然而,尽管这个问题sweep解决了似乎仍然存在的问题,但apply我不知道他们是否在某种程度上可以互换.
那么,为了提高我对R的理解,有没有什么方法可以使用上述程序apply?
This is close:
t(apply(df, 1, `*`, c(5,10)))
Run Code Online (Sandbox Code Playgroud)
The row names are lost but otherwise the output is the same
> t(apply(df, 1, '*', c(5,10)))
a b
[1,] 5 20
[2,] 10 30
[3,] 15 40
Run Code Online (Sandbox Code Playgroud)
To break this down, say we were doing this by hand for the first row of df, we'd write
> df[1, ] * c(5, 10)
a b
1 5 20
Run Code Online (Sandbox Code Playgroud)
which is the same as calling the '*'() function with arguments df[1, ] and c(5, 10)
> '*'(df[1, ], c(5, 10))
a b
1 5 20
Run Code Online (Sandbox Code Playgroud)
From this, we have enough to set up an apply() call:
MARGIN = 1,'*'() so FUN = '*'c(5,10), to '*'(), which we do via the ... argument of apply().The only extra thing to realise is how apply() sticks together the vector resulting from each "iteration"; here they are bound column-wise and hence we need to transpose the result from apply() so that we get the same output as sweep().