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

問題:

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等}如何將函數應用於輸入/分組輸入,輸出將是什麼樣,甚至輸入是什麼-因此我常常只是遍歷全部這些,直到獲得想要的東西。 app

Can someone explain how to use which one when? 誰能解釋何時使用哪個? ide

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具備多元素輸出,則爲您提供矩陣 ui

  2. lapply(vec, f) : same as sapply , but output is a list? lapply(vec, f) :與sapply相同,可是輸出是一個列表? spa

  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取代全部這些徹底? .net


解決方案:

參考一: https://stackoom.com/question/EhzZ/分組功能-tapply-by-aggregate-和-apply系列
參考二: https://oldbug.net/q/EhzZ/Grouping-functions-tapply-by-aggregate-and-the-apply-family
相關文章
相關標籤/搜索