2012-07-30 10 views
5

Angenommen, wir einen Datenrahmen, die wieeinen Datenrahmen umformen --- Ändern Zeilen in Spalten

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 

sieht Wir möchten diese neu zu gestalten, so dass jede Zeile einen repräsentiert (Zustand und) Kreis, eher als eine County-Industrie, mit Spalten construction.employment, construction.establishments, und analoge Versionen für die Herstellung. Was ist ein effizienter Weg dies zu tun?

Eine Möglichkeit ist

construction <- data[data$industry == "construction", ] 
names(construction)[4:5] <- c("construction.employment", "construction.establishments") 

Und in ähnlicher Weise für die Herstellung der Teilmenge, dann tun Sie eine Zusammenführung. Das ist nicht so schlimm, wenn es nur zwei Branchen gibt, aber stellen Sie sich vor, dass es 14 gibt; dieser Prozess würde mühsam werden (obwohl dies weniger durch Verwendung einer for Schleife über die Pegel von industry gemacht wird).

Irgendwelche anderen Ideen?

Antwort

7

Dies kann in der Basis R reshape erfolgen, wenn ich das richtig verstehe Ihre Frage:

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

Auch die reshape Paket mit:

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

Nachgeben:

> 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 persönlich benutze die basis reshape, also hätte ich das wahrscheinlich mit reshape2 (Wickham) gezeigt, aber vergessen, dass es a reshape2 Paket. Etwas anders:

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

Ah, okay, ich benutzte '.' anstelle von' ... ', also funktionierte es nicht. Vielen Dank! – Charlie

Verwandte Themen