问题:
Whenever I want to do something "map"py in R, I usually try to use a function in the apply
family. 每当我想在R中做“ map” py任务时,我通常都会尝试在apply
系列中使用一个函数。
However, I've never quite understood the differences between them -- how { sapply
, lapply
, etc.} apply the function to the input/grouped input, what the output will look like, or even what the input can be -- so I often just go through them all until I get what I want. 但是,我从未完全理解它们之间的区别-{ sapply
, lapply
等}如何将函数应用于输入/分组输入,输出将是什么样,甚至输入是什么-所以我经常只是遍历所有这些,直到得到想要的东西。
Can someone explain how to use which one when? 谁能解释什么时候使用哪一个?
My current (probably incorrect/incomplete) understanding is... 我目前(可能不正确/不完整)的理解是...
sapply(vec, f)
: input is a vector.sapply(vec, f)
:输入是向量。 output is a vector/matrix, where elementi
isf(vec[i])
, giving you a matrix iff
has a multi-element output 输出是一个向量/矩阵,其中元素i
为f(vec[i])
,如果f
具有多元素输出,则为您提供矩阵lapply(vec, f)
: same assapply
, but output is a list?lapply(vec, f)
:与sapply
相同,但是输出是一个列表?-
apply(matrix, 1/2, f)
: input is a matrix.apply(matrix, 1/2, f)
:输入是一个矩阵。 output is a vector, where elementi
is f(row/col i of the matrix) 输出是一个向量,其中元素i
为f(矩阵的行/列i) -
tapply(vector, grouping, f)
: output is a matrix/array, where an element in the matrix/array is the value off
at a groupingg
of the vector, andg
gets pushed to the row/col namestapply(vector, grouping, f)
:输出是一个矩阵/数组,其中矩阵/数组中的元素是向量分组g
处的f
值,并且g
被推到行/列名 -
by(dataframe, grouping, f)
: letg
be a grouping.by(dataframe, grouping, f)
:令g
为一个分组。 applyf
to each column of the group/dataframe. 将f
应用于组/数据框的每一列。 pretty print the grouping and the value off
at each column. 在每列漂亮地打印分组和f
的值。 -
aggregate(matrix, grouping, f)
: similar toby
, but instead of pretty printing the output, aggregate sticks everything into a dataframe.aggregate(matrix, grouping, f)
:类似于by
,但是aggregate不会将输出漂亮地打印by
,而是将所有内容粘贴到数据框中。
Side question: I still haven't learned plyr or reshape -- would plyr
or reshape
replace all of these entirely? 侧问题:我还没有学会plyr或重塑-将plyr
或reshape
取代所有这些完全?
解决方案:
参考一: https://stackoom.com/question/EhzZ/分组功能-tapply-by-aggregate-和-apply系列参考二: https://oldbug.net/q/EhzZ/Grouping-functions-tapply-by-aggregate-and-the-apply-family
来源:oschina
链接:https://my.oschina.net/stackoom/blog/4314984