1112

每当我想在 R 中做一些“map”py 的事情时,我通常会尝试使用apply家族中的一个函数。

但是,我从来没有完全理解它们之间的区别—— { sapply, lapply, etc.} 如何将函数应用于输入/分组输入,输出看起来像什么,甚至输入可以是什么——所以我经常只是通过它们,直到我得到我想要的。

有人可以解释如何在什么时候使用哪一个吗?

我目前(可能不正确/不完整)的理解是......

  1. sapply(vec, f): 输入是一个向量。output 是一个向量/矩阵,其中 elementi是,如果有一个多元素输出,则f(vec[i])给你一个矩阵f

  2. lapply(vec, f): 和 一样sapply,但是输出是一个列表?

  3. apply(matrix, 1/2, f): 输入是一个矩阵。输出是一个向量,其中元素i是 f(矩阵的行/列 i)
  4. tapply(vector, grouping, f):输出是矩阵/数组,其中矩阵/数组中的元素是向量f分组的值,并被推送到行/列名称gg
  5. by(dataframe, grouping, f): 让我们g成为一个分组。适用f于组/数据框的每一列。漂亮地打印每列的分组和值f
  6. aggregate(matrix, grouping, f): 类似于by,但不是漂亮地打印输出,而是聚合将所有内容粘贴到数据框中。

附带问题:我还没有学习 plyr 或 reshape - 会plyrreshape完全取代所有这些?

4

10 回答 10

1403

R 有许多 *apply 函数,这些函数在帮助文件(例如?apply)中有详细描述。但是,它们的数量已经足够多,以至于初学者可能很难决定哪一个适合他们的情况,甚至很难记住它们。他们可能有一种普遍的感觉,即“我应该在这里使用 *apply 函数”,但一开始很难让它们保持一致。

尽管事实(在其他答案中指出)*apply 系列的大部分功能都包含在非常流行的plyr包中,但基本功能仍然有用且值得了解。

该答案旨在充当新用户的一种路标,以帮助将他们引导至针对其特定问题的正确 *apply 功能。请注意,这并不是为了简单地反刍或替换 R 文档!希望这个答案可以帮助您确定哪个 *apply 功能适合您的情况,然后由您来进一步研究它。除了一个例外,将不会解决性能差异。

  • apply -当您想将函数应用于矩阵的行或列(以及更高维的类似物)时;通常不建议用于数据帧,因为它会首先强制转换为矩阵。

     # Two dimensional matrix
     M <- matrix(seq(1,16), 4, 4)
    
     # apply min to rows
     apply(M, 1, min)
     [1] 1 2 3 4
    
     # apply max to columns
     apply(M, 2, max)
     [1]  4  8 12 16
    
     # 3 dimensional array
     M <- array( seq(32), dim = c(4,4,2))
    
     # Apply sum across each M[*, , ] - i.e Sum across 2nd and 3rd dimension
     apply(M, 1, sum)
     # Result is one-dimensional
     [1] 120 128 136 144
    
     # Apply sum across each M[*, *, ] - i.e Sum across 3rd dimension
     apply(M, c(1,2), sum)
     # Result is two-dimensional
          [,1] [,2] [,3] [,4]
     [1,]   18   26   34   42
     [2,]   20   28   36   44
     [3,]   22   30   38   46
     [4,]   24   32   40   48
    

    如果您想要二维矩阵的行/列均值或总和,请务必研究高度优化的、闪电般快速的colMeansrowMeanscolSumsrowSums

  • lapply -当您想依次将函数应用于列表的每个元素并获取列表时。

    这是许多其他 *apply 函数的主力。剥开他们的代码,你会经常在lapply下面找到。

     x <- list(a = 1, b = 1:3, c = 10:100) 
     lapply(x, FUN = length) 
     $a 
     [1] 1
     $b 
     [1] 3
     $c 
     [1] 91
     lapply(x, FUN = sum) 
     $a 
     [1] 1
     $b 
     [1] 6
     $c 
     [1] 5005
    
  • sapply -当你想依次对列表的每个元素应用一个函数,但你想要一个向量,而不是一个列表。

    如果您发现自己在打字unlist(lapply(...)),请停下来考虑一下 sapply

     x <- list(a = 1, b = 1:3, c = 10:100)
     # Compare with above; a named vector, not a list 
     sapply(x, FUN = length)  
     a  b  c   
     1  3 91
    
     sapply(x, FUN = sum)   
     a    b    c    
     1    6 5005 
    

    在更高级的使用中sapply,如果合适,它将尝试将结果强制转换为多维数组。例如,如果我们的函数返回相同长度的向量,sapply则将它们用作矩阵的列:

     sapply(1:5,function(x) rnorm(3,x))
    

    如果我们的函数返回一个二维矩阵,sapply本质上将做同样的事情,将每个返回的矩阵视为一个长向量:

     sapply(1:5,function(x) matrix(x,2,2))
    

    除非我们指定simplify = "array",否则它将使用各个矩阵来构建多维数组:

     sapply(1:5,function(x) matrix(x,2,2), simplify = "array")
    

    当然,这些行为中的每一个都取决于我们的函数返回相同长度或维度的向量或矩阵。

  • vapply -当您想使用sapply但可能需要从代码中提高一些速度或想要更多类型安全时。

    对于vapply,您基本上给 R 一个示例,说明您的函数将返回什么样的东西,这可以节省一些时间来强制返回值以适应单个原子向量。

     x <- list(a = 1, b = 1:3, c = 10:100)
     #Note that since the advantage here is mainly speed, this
     # example is only for illustration. We're telling R that
     # everything returned by length() should be an integer of 
     # length 1. 
     vapply(x, FUN = length, FUN.VALUE = 0L) 
     a  b  c  
     1  3 91
    
  • mapply -当您有多个数据结构(例如向量、列表)并且您希望将函数应用于每个的第一个元素,然后是每个的第二个元素等时,将结果强制转换为向量/数组,如sapply.

    这是多变量的,因为您的函数必须接受多个参数。

     #Sums the 1st elements, the 2nd elements, etc. 
     mapply(sum, 1:5, 1:5, 1:5) 
     [1]  3  6  9 12 15
     #To do rep(1,4), rep(2,3), etc.
     mapply(rep, 1:4, 4:1)   
     [[1]]
     [1] 1 1 1 1
    
     [[2]]
     [1] 2 2 2
    
     [[3]]
     [1] 3 3
    
     [[4]]
     [1] 4
    
  • Map - with的包装器,因此保证返回一个列表。mapplySIMPLIFY = FALSE

     Map(sum, 1:5, 1:5, 1:5)
     [[1]]
     [1] 3
    
     [[2]]
     [1] 6
    
     [[3]]
     [1] 9
    
     [[4]]
     [1] 12
    
     [[5]]
     [1] 15
    
  • rapply -当您想要将函数应用于嵌套列表结构的每个元素时,递归。

    为了让您了解它的罕见rapply性,我在第一次发布此答案时忘记了它!显然,我敢肯定很多人都在使用它,但是 YMMV。rapply最好使用用户定义的函数来说明:

     # Append ! to string, otherwise increment
     myFun <- function(x){
         if(is.character(x)){
           return(paste(x,"!",sep=""))
         }
         else{
           return(x + 1)
         }
     }
    
     #A nested list structure
     l <- list(a = list(a1 = "Boo", b1 = 2, c1 = "Eeek"), 
               b = 3, c = "Yikes", 
               d = list(a2 = 1, b2 = list(a3 = "Hey", b3 = 5)))
    
    
     # Result is named vector, coerced to character          
     rapply(l, myFun)
    
     # Result is a nested list like l, with values altered
     rapply(l, myFun, how="replace")
    
  • tapply -当您想将函数应用于向量的子集并且子由某个其他向量定义时,通常是一个因子。

    *apply 家族的害群之马。帮助文件中“ragged array”这个短语的使用可能有点令人困惑,但实际上很简单。

    一个向量:

     x <- 1:20
    

    定义组的因子(相同长度!):

     y <- factor(rep(letters[1:5], each = 4))
    

    x将定义的每个子组中的值相加y

     tapply(x, y, sum)  
      a  b  c  d  e  
     10 26 42 58 74 
    

    可以处理更复杂的示例,其中子组由多个因素列表的唯一组合定义。tapply在精神上类似于 R ( aggregate, by, ave,ddply等) 中常见的 split-apply-combine 函数。因此它的害群之马。

于 2011-08-21T22:50:17.290 回答
202

在旁注中,这里是各种plyr功能与基本功能相对应的方式*apply(从 plyr 网页http://had.co.nz/plyr/的介绍到 plyr 文档)

Base function   Input   Output   plyr function 
---------------------------------------
aggregate        d       d       ddply + colwise 
apply            a       a/l     aaply / alply 
by               d       l       dlply 
lapply           l       l       llply  
mapply           a       a/l     maply / mlply 
replicate        r       a/l     raply / rlply 
sapply           l       a       laply 

的目标之一plyr是为每个函数提供一致的命名约定,在函数名称中编码输入和输出数据类型。它还提供了输出的一致性,因为输出dlply()很容易通过ldply()以产生有用的输出等。

从概念上讲,学习plyr并不比理解基本*apply功能更难。

plyrreshape功能在我的日常使用中几乎取代了所有这些功能。但是,同样来自 Intro to Plyr 文档:

相关功能tapplysweep没有对应的功能plyr,依然有用。merge对于将摘要与原始数据结合起来很有用。

于 2010-08-17T19:20:09.227 回答
142

来自http://www.slideshare.net/hadley/plyr-one-data-analytic-strategy的幻灯片 21 :

应用, sapply, lapply, by, 聚合

(希望很明显apply对应于@Hadleyaaply和@Hadley 等。如果你没有从这张图片中得到它,同一张幻灯片的幻灯片 20 会澄清。)aggregateddply

(左边是输入,上面是输出)

于 2011-10-09T05:29:32.633 回答
111

首先从Joran 的出色回答开始——怀疑任何事情都可以做得更好。

那么下面的助记符可能有助于记住它们之间的区别。虽然有些是显而易见的,但有些可能不那么明显——因为这些你会在 Joran 的讨论中找到理由。

助记符

  • lapply是一个列表应用,它作用于列表或向量并返回一个列表。
  • sapply是一个简单 lapply的(如果可能,函数默认返回向量或矩阵)
  • vapply经过验证的应用(允许预先指定返回对象类型)
  • rapply是嵌套列表的递归应用,即列表中的列表
  • tapply标记应用,其中标记标识子集
  • apply通用的:将函数应用于矩阵的行或列(或更一般地,应用于数组的维度)

建立正确的背景

如果使用apply家庭对您来说仍然感觉有点陌生,那么可能是您错过了一个关键观点。

这两篇文章可以提供帮助。它们为激发函数族提供的函数式编程技术提供了必要的背景apply

Lisp 的用户会立即认出这个范式。如果您不熟悉 Lisp,一旦您了解了 FP,您将获得在 R 中使用的强大观点——并且apply会更有意义。

于 2014-04-25T00:20:19.703 回答
58

因为我意识到这篇文章的(非常优秀的)答案缺乏byaggregate解释。这是我的贡献。

经过

by但是,如文档中所述,该函数可以作为tapply. by当我们想要计算一个tapply无法处理的任务时,就会出现的力量。一个例子是这段代码:

ct <- tapply(iris$Sepal.Width , iris$Species , summary )
cb <- by(iris$Sepal.Width , iris$Species , summary )

 cb
iris$Species: setosa
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  2.300   3.200   3.400   3.428   3.675   4.400 
-------------------------------------------------------------- 
iris$Species: versicolor
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  2.000   2.525   2.800   2.770   3.000   3.400 
-------------------------------------------------------------- 
iris$Species: virginica
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  2.200   2.800   3.000   2.974   3.175   3.800 


ct
$setosa
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  2.300   3.200   3.400   3.428   3.675   4.400 

$versicolor
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  2.000   2.525   2.800   2.770   3.000   3.400 

$virginica
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  2.200   2.800   3.000   2.974   3.175   3.800 

如果我们打印这两个对象ctcb,我们“基本上”得到相同的结果,唯一的区别在于它们的显示方式和不同的属性,class分别bycbarrayct

正如我所说,by当我们不能使用时,力量就会出现tapply;以下代码是一个示例:

 tapply(iris, iris$Species, summary )
Error in tapply(iris, iris$Species, summary) : 
  arguments must have same length

R 说参数必须具有相同的长度,例如“我们想要计算沿因子summary中的所有变量的”:但 R 不能这样做,因为它不知道如何处理。irisSpecies

使用by函数 R 为类调度一个特定的方法data frame,然后让summary函数工作,即使第一个参数的长度(以及类型也是)不同。

bywork <- by(iris, iris$Species, summary )

bywork
iris$Species: setosa
  Sepal.Length    Sepal.Width     Petal.Length    Petal.Width          Species  
 Min.   :4.300   Min.   :2.300   Min.   :1.000   Min.   :0.100   setosa    :50  
 1st Qu.:4.800   1st Qu.:3.200   1st Qu.:1.400   1st Qu.:0.200   versicolor: 0  
 Median :5.000   Median :3.400   Median :1.500   Median :0.200   virginica : 0  
 Mean   :5.006   Mean   :3.428   Mean   :1.462   Mean   :0.246                  
 3rd Qu.:5.200   3rd Qu.:3.675   3rd Qu.:1.575   3rd Qu.:0.300                  
 Max.   :5.800   Max.   :4.400   Max.   :1.900   Max.   :0.600                  
-------------------------------------------------------------- 
iris$Species: versicolor
  Sepal.Length    Sepal.Width     Petal.Length   Petal.Width          Species  
 Min.   :4.900   Min.   :2.000   Min.   :3.00   Min.   :1.000   setosa    : 0  
 1st Qu.:5.600   1st Qu.:2.525   1st Qu.:4.00   1st Qu.:1.200   versicolor:50  
 Median :5.900   Median :2.800   Median :4.35   Median :1.300   virginica : 0  
 Mean   :5.936   Mean   :2.770   Mean   :4.26   Mean   :1.326                  
 3rd Qu.:6.300   3rd Qu.:3.000   3rd Qu.:4.60   3rd Qu.:1.500                  
 Max.   :7.000   Max.   :3.400   Max.   :5.10   Max.   :1.800                  
-------------------------------------------------------------- 
iris$Species: virginica
  Sepal.Length    Sepal.Width     Petal.Length    Petal.Width          Species  
 Min.   :4.900   Min.   :2.200   Min.   :4.500   Min.   :1.400   setosa    : 0  
 1st Qu.:6.225   1st Qu.:2.800   1st Qu.:5.100   1st Qu.:1.800   versicolor: 0  
 Median :6.500   Median :3.000   Median :5.550   Median :2.000   virginica :50  
 Mean   :6.588   Mean   :2.974   Mean   :5.552   Mean   :2.026                  
 3rd Qu.:6.900   3rd Qu.:3.175   3rd Qu.:5.875   3rd Qu.:2.300                  
 Max.   :7.900   Max.   :3.800   Max.   :6.900   Max.   :2.500     

它确实有效,结果非常令人惊讶。它是一个类对象by,沿着Species(例如,对于它们中的每一个)计算summary每个变量的 。

请注意,如果第一个参数是 a data frame,则分派函数必须具有该类对象的方法。例如,如果我们将这段代码与mean函数一起使用,我们将拥有这段毫无意义的代码:

 by(iris, iris$Species, mean)
iris$Species: setosa
[1] NA
------------------------------------------- 
iris$Species: versicolor
[1] NA
------------------------------------------- 
iris$Species: virginica
[1] NA
Warning messages:
1: In mean.default(data[x, , drop = FALSE], ...) :
  argument is not numeric or logical: returning NA
2: In mean.default(data[x, , drop = FALSE], ...) :
  argument is not numeric or logical: returning NA
3: In mean.default(data[x, , drop = FALSE], ...) :
  argument is not numeric or logical: returning NA

总计的

aggregatetapply如果我们以这种方式使用它,则可以将其视为另一种不同的使用方式。

at <- tapply(iris$Sepal.Length , iris$Species , mean)
ag <- aggregate(iris$Sepal.Length , list(iris$Species), mean)

 at
    setosa versicolor  virginica 
     5.006      5.936      6.588 
 ag
     Group.1     x
1     setosa 5.006
2 versicolor 5.936
3  virginica 6.588

两个直接的区别是,的第二个参数aggregate 必须是一个列表,而tapply 可以(不是强制性的)是一个列表,并且的输出aggregate是一个数据帧,而一个tapply是一个array

的强大之aggregate处在于它可以轻松处理带有subset参数的数据子集,并且它还具有ts对象方法等formula

在某些情况下,这些元素aggregate更容易使用。tapply以下是一些示例(可在文档中找到):

ag <- aggregate(len ~ ., data = ToothGrowth, mean)

 ag
  supp dose   len
1   OJ  0.5 13.23
2   VC  0.5  7.98
3   OJ  1.0 22.70
4   VC  1.0 16.77
5   OJ  2.0 26.06
6   VC  2.0 26.14

我们可以达到同样的效果,tapply但语法稍微难一些,输出(在某些情况下)可读性较差:

att <- tapply(ToothGrowth$len, list(ToothGrowth$dose, ToothGrowth$supp), mean)

 att
       OJ    VC
0.5 13.23  7.98
1   22.70 16.77
2   26.06 26.14

还有其他时候我们不能使用byortapply我们必须使用aggregate.

 ag1 <- aggregate(cbind(Ozone, Temp) ~ Month, data = airquality, mean)

 ag1
  Month    Ozone     Temp
1     5 23.61538 66.73077
2     6 29.44444 78.22222
3     7 59.11538 83.88462
4     8 59.96154 83.96154
5     9 31.44828 76.89655

我们无法通过tapply一次调用获得先前的结果,但我们必须计算Month每个元素的平均值,然后将它们组合起来(还要注意我们必须调用na.rm = TRUE,因为函数的formula方法aggregate默认具有na.action = na.omit):

ta1 <- tapply(airquality$Ozone, airquality$Month, mean, na.rm = TRUE)
ta2 <- tapply(airquality$Temp, airquality$Month, mean, na.rm = TRUE)

 cbind(ta1, ta2)
       ta1      ta2
5 23.61538 65.54839
6 29.44444 79.10000
7 59.11538 83.90323
8 59.96154 83.96774
9 31.44828 76.90000

虽然by我们无法实现这一点,但实际上下面的函数调用会返回一个错误(但很可能它与提供的函数有关mean):

by(airquality[c("Ozone", "Temp")], airquality$Month, mean, na.rm = TRUE)

其他时候结果是相同的,差异只是在类中(然后它是如何显示/打印的,而不仅仅是——例如,如何对其进行子集化)对象:

byagg <- by(airquality[c("Ozone", "Temp")], airquality$Month, summary)
aggagg <- aggregate(cbind(Ozone, Temp) ~ Month, data = airquality, summary)

之前的代码实现了相同的目标和结果,在某些时候使用什么工具只是个人品味和需求的问题;前两个对象在子集方面有非常不同的需求。

于 2015-08-28T02:28:10.590 回答
39

有很多很好的答案讨论了每个功能的用例差异。没有一个答案讨论性能差异。这是合理的,因为各种函数期望不同的输入并产生不同的输出,但它们中的大多数都有一个通用的共同目标来按系列/组进行评估。我的答案将集中在性能上。由于上述来自向量的输入创建包含在时序中,apply因此也不测量函数。

我一次测试了两种不同的sum功能length。测试的音量为 50M 输入和 50K 输出。我还包括了两个当前流行的软件包,它们在提出问题时并未被广泛使用,data.table以及dplyr. 如果您的目标是获得良好的性能,两者都绝对值得一看。

library(dplyr)
library(data.table)
set.seed(123)
n = 5e7
k = 5e5
x = runif(n)
grp = sample(k, n, TRUE)

timing = list()

# sapply
timing[["sapply"]] = system.time({
    lt = split(x, grp)
    r.sapply = sapply(lt, function(x) list(sum(x), length(x)), simplify = FALSE)
})

# lapply
timing[["lapply"]] = system.time({
    lt = split(x, grp)
    r.lapply = lapply(lt, function(x) list(sum(x), length(x)))
})

# tapply
timing[["tapply"]] = system.time(
    r.tapply <- tapply(x, list(grp), function(x) list(sum(x), length(x)))
)

# by
timing[["by"]] = system.time(
    r.by <- by(x, list(grp), function(x) list(sum(x), length(x)), simplify = FALSE)
)

# aggregate
timing[["aggregate"]] = system.time(
    r.aggregate <- aggregate(x, list(grp), function(x) list(sum(x), length(x)), simplify = FALSE)
)

# dplyr
timing[["dplyr"]] = system.time({
    df = data_frame(x, grp)
    r.dplyr = summarise(group_by(df, grp), sum(x), n())
})

# data.table
timing[["data.table"]] = system.time({
    dt = setnames(setDT(list(x, grp)), c("x","grp"))
    r.data.table = dt[, .(sum(x), .N), grp]
})

# all output size match to group count
sapply(list(sapply=r.sapply, lapply=r.lapply, tapply=r.tapply, by=r.by, aggregate=r.aggregate, dplyr=r.dplyr, data.table=r.data.table), 
       function(x) (if(is.data.frame(x)) nrow else length)(x)==k)
#    sapply     lapply     tapply         by  aggregate      dplyr data.table 
#      TRUE       TRUE       TRUE       TRUE       TRUE       TRUE       TRUE 

# print timings
as.data.table(sapply(timing, `[[`, "elapsed"), keep.rownames = TRUE
              )[,.(fun = V1, elapsed = V2)
                ][order(-elapsed)]
#          fun elapsed
#1:  aggregate 109.139
#2:         by  25.738
#3:      dplyr  18.978
#4:     tapply  17.006
#5:     lapply  11.524
#6:     sapply  11.326
#7: data.table   2.686
于 2015-12-08T22:42:43.753 回答
31

尽管这里有所有很好的答案,但还有 2 个基本功能值得一提,有用的outer功能和晦涩的eapply功能

outer是一个非常有用的功能,隐藏起来是一个更普通的功能。如果您阅读outer其描述的帮助说明:

The outer product of the arrays X and Y is the array A with dimension  
c(dim(X), dim(Y)) where element A[c(arrayindex.x, arrayindex.y)] =   
FUN(X[arrayindex.x], Y[arrayindex.y], ...).

这使得它看起来只对线性代数类型的东西有用。但是,它的使用非常类似于mapply将函数应用于两个输入向量。不同之处在于,mapply它将将该函数应用于前两个元素,然后是后两个元素,以此类推,而outer将函数应用于第一个向量中的一个元素和第二个向量中的一个元素的每个组合。例如:

 A<-c(1,3,5,7,9)
 B<-c(0,3,6,9,12)

mapply(FUN=pmax, A, B)

> mapply(FUN=pmax, A, B)
[1]  1  3  6  9 12

outer(A,B, pmax)

 > outer(A,B, pmax)
      [,1] [,2] [,3] [,4] [,5]
 [1,]    1    3    6    9   12
 [2,]    3    3    6    9   12
 [3,]    5    5    6    9   12
 [4,]    7    7    7    9   12
 [5,]    9    9    9    9   12

当我有一个值向量和一个条件向量并希望查看哪些值满足哪些条件时,我个人使用了它。

申请

eapply就像lapply它不是将函数应用于列表中的每个元素,而是将函数应用于环境中的每个元素。例如,如果您想在全局环境中查找用户定义函数的列表:

A<-c(1,3,5,7,9)
B<-c(0,3,6,9,12)
C<-list(x=1, y=2)
D<-function(x){x+1}

> eapply(.GlobalEnv, is.function)
$A
[1] FALSE

$B
[1] FALSE

$C
[1] FALSE

$D
[1] TRUE 

坦率地说,我并不经常使用它,但如果您正在构建大量包或创建大量环境,它可能会派上用场。

于 2016-05-16T03:59:13.613 回答
27

这也许值得一提aveavetapply的友好表弟。它以一种可以直接插入数据框的形式返回结果。

dfr <- data.frame(a=1:20, f=rep(LETTERS[1:5], each=4))
means <- tapply(dfr$a, dfr$f, mean)
##  A    B    C    D    E 
## 2.5  6.5 10.5 14.5 18.5 

## great, but putting it back in the data frame is another line:

dfr$m <- means[dfr$f]

dfr$m2 <- ave(dfr$a, dfr$f, FUN=mean) # NB argument name FUN is needed!
dfr
##   a f    m   m2
##   1 A  2.5  2.5
##   2 A  2.5  2.5
##   3 A  2.5  2.5
##   4 A  2.5  2.5
##   5 B  6.5  6.5
##   6 B  6.5  6.5
##   7 B  6.5  6.5
##   ...

基本包中没有任何东西适用ave于整个数据帧(by就像tapply数据帧一样)。但你可以捏造它:

dfr$foo <- ave(1:nrow(dfr), dfr$f, FUN=function(x) {
    x <- dfr[x,]
    sum(x$m*x$m2)
})
dfr
##     a f    m   m2    foo
## 1   1 A  2.5  2.5    25
## 2   2 A  2.5  2.5    25
## 3   3 A  2.5  2.5    25
## ...
于 2014-11-06T00:00:25.190 回答
15

我最近发现了一个相当有用的sweep功能,为了完整起见将它添加到这里:

基本思想是按行或按列扫描数组并返回修改后的数组。一个例子可以清楚地说明这一点(来源:datacamp):

假设您有一个矩阵并希望按列对其进行标准化

dataPoints <- matrix(4:15, nrow = 4)

# Find means per column with `apply()`
dataPoints_means <- apply(dataPoints, 2, mean)

# Find standard deviation with `apply()`
dataPoints_sdev <- apply(dataPoints, 2, sd)

# Center the points 
dataPoints_Trans1 <- sweep(dataPoints, 2, dataPoints_means,"-")

# Return the result
dataPoints_Trans1
##      [,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

# Normalize
dataPoints_Trans2 <- sweep(dataPoints_Trans1, 2, dataPoints_sdev, "/")

# Return the result
dataPoints_Trans2
##            [,1]       [,2]       [,3]
## [1,] -1.1618950 -1.1618950 -1.1618950
## [2,] -0.3872983 -0.3872983 -0.3872983
## [3,]  0.3872983  0.3872983  0.3872983
## [4,]  1.1618950  1.1618950  1.1618950

注意:对于这个简单的例子,同样的结果当然可以更容易地实现
apply(dataPoints, 2, scale)

于 2017-06-16T16:03:27.173 回答
7

在最近在 CRAN 上发布的collapse包中,我尝试将大多数常见的应用功能压缩成两个函数:

  1. dapply(Data-Apply)将函数应用于矩阵和 data.frames 的行或(默认)列,并且(默认)返​​回具有相同类型和相同属性的对象(除非每个计算的结果是原子的并且drop = TRUE)。性能与lapplydata.frame 列相当,比apply矩阵行或列快约 2 倍。并行性可通过mclapply(仅适用于 MAC)获得。

句法:

dapply(X, FUN, ..., MARGIN = 2, parallel = FALSE, mc.cores = 1L, 
       return = c("same", "matrix", "data.frame"), drop = TRUE)

例子:

# Apply to columns:
dapply(mtcars, log)
dapply(mtcars, sum)
dapply(mtcars, quantile)
# Apply to rows:
dapply(mtcars, sum, MARGIN = 1)
dapply(mtcars, quantile, MARGIN = 1)
# Return as matrix:
dapply(mtcars, quantile, return = "matrix")
dapply(mtcars, quantile, MARGIN = 1, return = "matrix")
# Same for matrices ...
  1. BY是一个 S3 泛型,用于使用向量、矩阵和 data.frame 方法进行拆分-应用-组合计算。它明显快于tapply,by并且(在大数据上aggregate也比,更快)。plyrdplyr

句法:

BY(X, g, FUN, ..., use.g.names = TRUE, sort = TRUE,
   expand.wide = FALSE, parallel = FALSE, mc.cores = 1L,
   return = c("same", "matrix", "data.frame", "list"))

例子:

# Vectors:
BY(iris$Sepal.Length, iris$Species, sum)
BY(iris$Sepal.Length, iris$Species, quantile)
BY(iris$Sepal.Length, iris$Species, quantile, expand.wide = TRUE) # This returns a matrix 
# Data.frames
BY(iris[-5], iris$Species, sum)
BY(iris[-5], iris$Species, quantile)
BY(iris[-5], iris$Species, quantile, expand.wide = TRUE) # This returns a wider data.frame
BY(iris[-5], iris$Species, quantile, return = "matrix") # This returns a matrix
# Same for matrices ...

分组变量列表也可以提供给g.

谈论性能:collapse的一个主要目标是促进 R 中的高性能编程,并超越拆分-应用-组合。为此,该包具有一整套基于 C++ 的快速通用函数:fmean, fmedian, fmode, fsum, fprod, fsd, fvar, fmin, fmax, ffirst, flast, fNobs, fNdistinct, fscale, fbetween, fwithin, fHDbetween, fHDwithin,flag和. 他们在一次通过数据的过程中执行分组计算(即没有拆分和重组)。fdifffgrowth

句法:

fFUN(x, g = NULL, [w = NULL,] TRA = NULL, [na.rm = TRUE,] use.g.names = TRUE, drop = TRUE)

例子:

v <- iris$Sepal.Length
f <- iris$Species

# Vectors
fmean(v)             # mean
fmean(v, f)          # grouped mean
fsd(v, f)            # grouped standard deviation
fsd(v, f, TRA = "/") # grouped scaling
fscale(v, f)         # grouped standardizing (scaling and centering)
fwithin(v, f)        # grouped demeaning

w <- abs(rnorm(nrow(iris)))
fmean(v, w = w)      # Weighted mean
fmean(v, f, w)       # Weighted grouped mean
fsd(v, f, w)         # Weighted grouped standard-deviation
fsd(v, f, w, "/")    # Weighted grouped scaling
fscale(v, f, w)      # Weighted grouped standardizing
fwithin(v, f, w)     # Weighted grouped demeaning

# Same using data.frames...
fmean(iris[-5], f)                # grouped mean
fscale(iris[-5], f)               # grouped standardizing
fwithin(iris[-5], f)              # grouped demeaning

# Same with matrices ...

在包小插曲中,我提供了基准。使用快速函数编程比使用dplyrdata.table编程要快得多,尤其是在较小的数据上,而且在大数据上也是如此。

于 2020-03-20T07:22:45.597 回答