【发布时间】:2020-07-07 01:32:06
【问题描述】:
我有一个如下的data.table
panelID = c(1:50)
year= c(2001:2010)
country = c("NLD", "BEL", "GER")
urban = c("A", "B", "C")
indust = c("D", "E", "F")
sizes = c(1,2,3,4,5)
n <- 2
library(data.table)
set.seed(123)
DT <- data.table(panelID = rep(sample(panelID), each = n),
country = rep(sample(country, length(panelID), replace = T), each = n),
year = c(replicate(length(panelID), sample(year, n))),
some_NA = sample(0:5, 6),
some_NA_factor = sample(0:5, 6),
industry = rep(sample(indust, length(panelID), replace = T), each = n),
urbanisation = rep(sample(urban, length(panelID), replace = T), each = n),
size = rep(sample(sizes, length(panelID), replace = T), each = n),
norm = round(runif(100)/10,2),
sales= round(rnorm(10,10,10),2),
Happiness = sample(10,10),
Sex = round(rnorm(10,0.75,0.3),2),
Age = sample(100,100),
Educ = round(rnorm(10,0.75,0.3),2))
DT [, uniqueID := .I] # Creates a unique ID
DT[DT == 0] <- NA
DT$sales[DT$sales< 0] <- NA
DT <- as.data.frame(DT)
setDT(DT)[,Mean_Sales_pergroup := mean(sales, na.rm=TRUE), by=c("industry", "year")]
现在我想比较多年来Mean_Sales_pergroup 与industry 的不同之处,所以我想尝试一下:
table(DT$Mean_Sales_pergroup, DT$year)
但这给了我:
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
2.11 0 0 0 0 0 0 1 0 0 0
2.18 0 0 0 0 0 0 0 0 0 1
2.61 2 0 0 0 0 0 0 1 0 0
3.6775 0 0 0 0 4 0 0 0 0 0
...
14.19 0 0 0 0 0 0 0 2 0 0
这当然不是什么信息。
我该怎么做才能得到类似的东西:
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
Industry D ..
Industry E
Industry F
编辑:
@rg255 的评论给出:
dcast(DT, industry ~ year, value.var = "Mean_Sales_pergroup")
Aggregate function missing, defaulting to 'length'
industry 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
1: D 1 1 5 5 3 4 1 1 6 1
2: E 2 5 5 3 4 3 3 1 3 5
3: F 1 6 2 3 4 7 5 2 4 4
【问题讨论】:
-
我不确定你期望得到的数字,但确实:
dcast(DT, industry ~ year, value.var = "Mean_Sales_pergroup")做你想要/期望的? -
@rg255 感谢您的评论!这已经是朝着正确方向迈出的一步,但我想我希望看到的是手段而不是手段的出现。
-
这就是我的目标,但在手机上工作并不容易看到/确定我是否成功:D
标签: r data.table reshape mean