这里的. 类似于在data.table 中调用list。它正在创建一个汇总输出列
.(Previous_Sales=sum(Sales))
或者list
list(Previous_Sales=sum(Sales))
在dplyr 中,类似的语法是
summarise(Previous_Sales = sum(Sales))
以及用于创建列/修改现有列的用户
mutate(Previous_Sales = sum(Sales))
使用data.table,使用:= 完成更新/创建列
Previous_Sales := sum(Sales)
同样,by 也将是列名的list
by = list(Category, send_Date=floor_date(send_Date,unit='week',week_start = 7)
我们也可以使用
by = .(Category, send_Date=floor_date(send_Date,unit='week',week_start = 7)
在data.table的上下文中,语法顺序一致
dt[i, j, by]
其中i,是我们指定行条件的地方,j,我们在列/列和by分组列上应用函数。使用iris的简单示例
as.data.table(iris)[Sepal.Length < 5, .(Sum = sum(Sepal.Width)), by = Species]
i 是Sepal.Length < 5 它只选择满足条件的行到sum 'Sepal.Width' (在那些行中),并且由于提供了by 选项,它将执行@每个“物种”的“Sepal.Width”的 987654348@ 导致 3 行(这里有 3 个唯一的“物种”)。我们也可以在没有i 选项的情况下通过在j 本身中进行子集化来做到这一点
as.data.table(iris)[, .(Sum = sum(Sepal.Width[Sepal.Length < 5])), by = Species]
使用summariseation,这两个都可以,但是如果我们做一个作业(:=),那就不同了
as.data.table(iris)[Sepal.Length < 5, Sum := sum(Sepal.Width), by = Species]
这将创建一个“Sum”列,并仅在“Sepal.Length and all other row elements will beNA”处填充sum 值。如果我们做第二个选项
as.data.table(iris)[, Sum := sum(Sepal.Width[Sepal.Length < 5]), by = Species]
不会有任何 NA 元素,因为它在 j 内进行子集化,以便为每个“物种”创建单个 sum 值