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

  • 本文关键字:数据 填充 层次结构 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    )

也许这会有所帮助

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

使用 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

最新更新