【发布时间】:2016-10-05 18:32:20
【问题描述】:
只是好奇是否有我想念的偷偷摸摸的方法。
library(plyr)
library(data.table)
dfx <- data.frame(
group = c(rep('A', 8), rep('B', 15), rep('C', 6)),
sex = sample(c("M", "F"), size = 29, replace = TRUE),
age = runif(n = 29, min = 18, max = 54) ,
score = runif( n = 29 ) ,
weight = sample( 0:1 , 29 , replace = TRUE )
)
dt_dfx <- as.data.table(dfx)
未加权平均比较
# mean of all columns not specified in by=
dt_dfx[ , lapply( .SD , mean ) , by = .(sex,group) ]
# here's how to match the data.table unweighted mean
ddply(dfx, .(group,sex), numcolwise(mean))
不知道如何使用plyr 来做到这一点
# weighted.mean of all columns not specified in by=
dt_dfx[ , lapply( .SD , weighted.mean , weight ) , by = .(sex,group) ]
# easy way to match the data.table weighted.mean?
谢谢大家
【问题讨论】:
-
protip:不要将
dfx声明为data.frame——只需使用data.table,它就会以data.table的形式诞生。如果您从data.frame开始,您可以使用setDT(dfx)通过引用(无副本)将其转换为data.table(无需使用<-重新分配)——转换就地完成。 -
因为
plyr对于这类事情已经过时了——谁在乎呢? -
我感觉到 XY 问题...
-
@eddi
dplyr那么呢?最新和最好的方法是什么? :) -
@AnthonyDamico 你已经拥有了最好的方法;)至于最新的
plyr-type 方法——当然,你dplyr中的can do it
标签: r data.table plyr