分组功能(tapply,by,aggregate)和* apply系列

自闭症网瘾萝莉.ら 提交于 2020-08-11 20:13:47

问题:

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. 但是,我从未完全理解它们之间的区别-{ sapplylapply等}如何将函数应用于输入/分组输入,输出将是什么样,甚至输入是什么-所以我经常只是遍历所有这些,直到得到想要的东西。

Can someone explain how to use which one when? 谁能解释什么时候使用哪一个?

My current (probably incorrect/incomplete) understanding is... 我目前(可能不正确/不完整)的理解是...

  1. sapply(vec, f) : input is a vector. sapply(vec, f) :输入是向量。 output is a vector/matrix, where element i is f(vec[i]) , giving you a matrix if f has a multi-element output 输出是一个向量/矩阵,其中元素if(vec[i]) ,如果f具有多元素输出,则为您提供矩阵

  2. lapply(vec, f) : same as sapply , but output is a list? lapply(vec, f) :与sapply相同,但是输出是一个列表?

  3. apply(matrix, 1/2, f) : input is a matrix. apply(matrix, 1/2, f) :输入是一个矩阵。 output is a vector, where element i is f(row/col i of the matrix) 输出是一个向量,其中元素i为f(矩阵的行/列i)
  4. tapply(vector, grouping, f) : output is a matrix/array, where an element in the matrix/array is the value of f at a grouping g of the vector, and g gets pushed to the row/col names tapply(vector, grouping, f) :输出是一个矩阵/数组,其中矩阵/数组中的元素是向量分组g处的f值,并且g被推到行/列名
  5. by(dataframe, grouping, f) : let g be a grouping. by(dataframe, grouping, f) :令g为一个分组。 apply f to each column of the group/dataframe. f应用于组/数据框的每一列。 pretty print the grouping and the value of f at each column. 在每列漂亮地打印分组和f的值。
  6. aggregate(matrix, grouping, f) : similar to by , 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或重塑-将plyrreshape取代所有这些完全?


解决方案:

参考一: https://stackoom.com/question/EhzZ/分组功能-tapply-by-aggregate-和-apply系列
参考二: https://oldbug.net/q/EhzZ/Grouping-functions-tapply-by-aggregate-and-the-apply-family
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!