R 创建信息更丰富的表输出
我有一个数据表,如下所示R 创建信息更丰富的表输出,r,data.table,reshape,mean,R,Data.table,Reshape,Mean,我有一个数据表,如下所示 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
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")]
但这给了我:
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(unique(DT[, .(industry, year, Mean_Sales_pergroup)]), ... ~ year)
给出所需的输出
industry 2001 2002 2003 2004 2005 2006 2007 2008
1: D 2.61 4.260 6.204 9.650000 10.7050 8.625000 2.110000 2.61
2: E 13.24 6.766 9.940 5.156667 3.6775 9.225000 4.606667 13.24
3: F 2.61 8.000 ...
因为每个组的
Mean\u Sales\u的唯一实例为0或1
对于行业
和年份
的每种可能组合,您还可以
解决方法如下:
dcast(DT, industry ~ year, fun = function(x) x[1], value.var = "Mean_Sales_pergroup")
我不确定您希望公布的数字,但确实:dcast(DT,industry~year,value.var=“Mean\u Sales\u pergroup”)
做您想做的/期望做的事?@rg255谢谢您的评论!这已经是朝着正确的方向迈出的一步,但我想我希望看到的是手段,而不是手段的出现。这正是我的目标,但在手机上工作不容易看到/计算出我是否成功:真不错!非常感谢。
dcast(DT, industry ~ year, fun = function(x) x[1], value.var = "Mean_Sales_pergroup")