R 如何在一个data.table语句中联接并获取组中的行数?
我试着去做R 如何在一个data.table语句中联接并获取组中的行数?,r,data.table,R,Data.table,我试着去做 library(data.table) customers <- data.table( id=c(1,2,3,4), # id of customers name=c("Frank","Hans","Peter","Markus"), age=c(22,34,64,19)) purchases <- data.
library(data.table)
customers <- data.table( id=c(1,2,3,4), # id of customers
name=c("Frank","Hans","Peter","Markus"),
age=c(22,34,64,19))
purchases <- data.table( id=c(1,2,3,4,5,6), # id of purchases
customer_id=c(1,2,4,2,1,5),
name=c("CD","hairdryer","book","glas","paper","chair"),
product_type=c("home","home","home","home","office","office")
)
purchases[customers, .N, by=product_type, on=c(customer_id = "id")]
purchases[customers, mean(age), by=product_type, on=c(customer_id = "id")]
但是得到
product_type N
1: home 4
2: NA 1
3: home 1
第二个命令应该进行连接,然后在产品类型上分组,并计算每个组的平均年龄。但是我得到的错误是未找到age
purchases[customers, mean(age), by=.EACHI, on=c(customer_id = "id")]
顺便说一句,效果非常好。试试购买[customers,on=c(customer\u id=“id”)][,.N,product\u type]
@akrun:当然可以,但我想把它放在一个命令中,这样速度就快了。否则我只能使用dplyr
。这有一个功能要求:@Make42我认为在dplyr
中,您需要使用更多的命令。@jangorecki:您缺少的效率点是:如果数据,最大的好处就是。table
知道我只对product\u-type
groups,它不必处理整个两个表,而只需在连接过程中处理相关列(已经!)。请尝试purchases[customers,on=c(customer\u id=“id”)[,.N,product\u-type]
@akrun:当然,但我希望将其放在一个命令中,这样速度会更快。否则我只能使用dplyr
。这有一个功能要求:@Make42我认为在dplyr
中,您需要使用更多的命令。@jangorecki:您缺少的效率点是:如果数据,最大的好处就是。table
知道我只对product\u type
groups,它不必处理整个两个表,而只需在连接过程中处理相关列(已经!)。
purchases[customers, mean(age), by=.EACHI, on=c(customer_id = "id")]