2012-07-30 22 views
5

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?

risposta

7

questo può essere fatto in base di R rimodellare, se ho ben capito la sua domanda:

reshape(data, direction="wide", idvar=c("state", "county"), timevar="industry") 
# state county employment.construction establishments.construction 
# 1  A  a      146       19 
# 3  A  b      121       10 
# 5  A  c      197       18 
# 7  A  d      98       30 
# employment.manufacturing establishments.manufacturing 
# 1      110       20 
# 3      90       27 
# 5      73       29 
# 7      102       19 
4

anche utilizzando il pacchetto Reshape:

library(reshape) 
m <- reshape::melt(data) 
cast(m, state + county~...) 

Cedendo:

> cast(m, state + county~...) 
    state county construction_employment construction_establishments manufacturing_employment manufacturing_establishments 
1  A  a      146       19      110       20 
2  A  b      121       10      90       27 
3  A  c      197       18      73       29 
4  A  d      98       30      102       19 

I personalmente uso la base di rimodellamento quindi probabilmente avrei dovuto mostrarlo usando reshape2 (Wickham) ma ho dimenticato che c'era un pacchetto reshape2. Leggermente diverso:

library(reshape2) 
m <- reshape2::melt(data) 
dcast(m, state + county~...) 
+0

Ah, okay, stavo usando '.' anziché' ... ', quindi non funzionava. Grazie! – Charlie

Problemi correlati