Ich habe eine Datentabelle wie folgt
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")]
Jetzt möchte ich vergleichen, wie sich die Mean_Sales_pergroup
Unterschiede im industry
Laufe der Jahre unterscheiden, also habe ich darüber nachgedacht, Folgendes zu versuchen:
table(DT$Mean_Sales_pergroup, DT$year)
Aber das gibt mir:
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
Was natürlich alles andere als informativ ist.
Was könnte ich tun, um so etwas zu bekommen:
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010
Industry D ..
Industry E
Industry F
BEARBEITEN:
@ rg255 Kommentar gibt:
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
Einzigartige Reihen machen und dann gießen
dcast(unique(DT[, .(industry, year, Mean_Sales_pergroup)]), ... ~ year)
Gibt die gewünschte Ausgabe
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 ...
Dieser Artikel stammt aus dem Internet. Bitte geben Sie beim Nachdruck die Quelle an.
Bei Verstößen wenden Sie sich bitte [email protected] Löschen.
Lass mich ein paar Worte sagen