从类别层次结构中填充数据框

时间:2015-01-25 20:31:53

标签: r

我在做地理数据分析。我有各州的数据,我想根据人口普查局的分组按区域和地区分组。这里有一个层次结构:区域,分区和状态,从大到小。

我想要做的是填写一个编码该信息的新数据框。 (然后我可以使用它作为参考,并清理数据。)我已经尝试了几种方法,但已经陷入困境。我感谢任何解决方案。

以下是分部列表:

pacific <- c('WA', 'OR', 'CA', 'AK', 'HI')
mountain <- c('MT', 'ID', 'WY', 'NV', 'UT', 'CO', 'AZ', 'NM')
w.n.central <- c('ND', 'SD', 'NE', 'KS', 'MN', 'IA', 'MO')
w.s.central <- c('TX', 'OK', 'AR', 'LA')
e.n.central <- c('WI', 'MI', 'IL', 'IN', 'OH')
e.s.central <- c('KY', 'TN', 'MS', 'AL')
mid.atlantic <- c('NY', 'PA', 'NJ')
new.england <- c('VT', 'NH', 'MA', 'CT', 'RI', 'ME')
south.atlantic <- c('WV', 'MD', 'DE', 'DC', 'VA', 'NC', 'SC', 'GA', 'FL')
divisions <- c(pacific, mountain, w.n.central, w.s.central, e.n.central, e.s.central, mid.atlantic, south.atlantic, new.england)

以及地区列表:

northeast <- c(new.england, mid.atlantic)
midwest <- c(e.n.central, w.n.central)
south <- c(south.atlantic, e.s.central, w.s.central)
west <- c(mountain, pacific)
regions <- c(northeast, midwest, south, west)

编辑:我更喜欢输出为三列(状态,分区,区域)的df。

编辑:由于状态数据集,整个任务最终变得不必要了。相反,我创建了以下内容:

data_frame(
state = state.abb,
state.name = state.name,
region = state.region,
division = state.division    )

2 个答案:

答案 0 :(得分:3)

可能有帮助

st <- state.abb
lst <- mget(regions) 
v1 <- unlist(lapply(names(lst), function(x) {
             x1 <- lst[[x]]
             setNames(rep(x, length(x1)),x1)}))
 reg <- unname(v1[st])

divisions1 <- c('pacific', 'mountain', 'w.n.central', 'w.s.central', 
  'e.n.central', 'e.s.central', 'mid.atlantic', 'south.atlantic', 
   'new.england')
lst2 <-  mget(divisions1)

v2 <- unlist(lapply(names(lst2), function(x) {
                    x1 <- lst2[[x]] 
                 setNames(rep(x, length(x1)),x1)}))

div <-  unname(v2[st])

dat <- data.frame(state=st, division=div, region=reg,
               stringsAsFactors=FALSE)
head(dat,3)
#   state    division region
#1    AL e.s.central  south
#2    AK     pacific   west
#3    AZ    mountain   west

答案 1 :(得分:2)

使用dplyr

library(dplyr)

chardiv <- c("pacific", "mountain", "w.n.central", "w.s.central", 
             "e.n.central", "e.s.central", "mid.atlantic", 
             "south.atlantic", "new.england")

dfdiv <- data.frame(state = unlist(mget(regions))) %>%
  mutate(regions = gsub("[0-9]*$", "", rownames(.)))

dfstate = data.frame(state = unlist(mget(chardiv))) %>%
  mutate(divisions = gsub("[0-9]*$", "", rownames(.)))

left_join(dfdiv, dfstate, by = "state")

你得到:

#> head(df, 10L)
#   state   regions    divisions
#1     VT northeast  new.england
#2     NH northeast  new.england
#3     MA northeast  new.england
#4     CT northeast  new.england
#5     RI northeast  new.england
#6     ME northeast  new.england
#7     NY northeast mid.atlantic
#8     PA northeast mid.atlantic
#9     NJ northeast mid.atlantic
#10    WI   midwest  e.n.central