Supponiamo di avere un frame di dati che assomigliaRimodellare un frame di dati --- cambiando righe per colonne
set.seed(7302012)
county <- rep(letters[1:4], each=2)
state <- rep(LETTERS[1], times=8)
industry <- rep(c("construction", "manufacturing"), 4)
employment <- round(rnorm(8, 100, 50), 0)
establishments <- round(rnorm(8, 20, 5), 0)
data <- data.frame(state, county, industry, employment, establishments)
state county industry employment establishments
1 A a construction 146 19
2 A a manufacturing 110 20
3 A b construction 121 10
4 A b manufacturing 90 27
5 A c construction 197 18
6 A c manufacturing 73 29
7 A d construction 98 30
8 A d manufacturing 102 19
Vorremmo rimodellare questo modo che ogni riga rappresenta un (stato e) regione, piuttosto che un'industria di contea, con le colonne construction.employment
, construction.establishments
e versioni analoghe per la produzione. Qual è un modo efficace per farlo?
Un modo è quello sottoinsieme
construction <- data[data$industry == "construction", ]
names(construction)[4:5] <- c("construction.employment", "construction.establishments")
E allo stesso modo per la produzione, poi fare una fusione. Non è così male se ci sono solo due industrie, ma immagina che ce ne siano 14; questo processo diventerebbe noioso (anche se reso meno utilizzando un ciclo for
sui livelli di industry
).
Altre idee?
Ah, okay, stavo usando '.' anziché' ... ', quindi non funzionava. Grazie! – Charlie