首页 > 解决方案 > 按组将一个变量分成多个

问题描述

为了在我的 felm 固定效应估计中包含州特定的年度趋势,我想为每个州创建一个单独的变量,第一年的值为 1,第二年的值为 2,依此类推,所有其他州的值为 0 . 我设法创建了一个满足所有这些要求的变量(示例中的“stateyear”),除了它只是所有状态的一个变量(参见示例)。有没有办法按组(state_geocode_id)将此变量拆分为许多变量,并将它们中的每一个设置为 0 以用于除各自的所有其他状态?

简化数据集:

d <- data.frame("100")
names(d) <- "state_geocode_id"
d$state_geocode_id <- as.character(d$state_geocode_id)
d <- rbind(d, "100", "100", "100", "101", "101", "101", "101", "102", "102", "102", "102")
d$municip <- c("1", "1", "2", "2", "3", "3", "4", "4", "5", "5", "6", "6")
d$year <- c("2000", "2001", "2000", "2001","2000", "2001", "2000", "2001", "2000", "2001", "2000", "2001")

添加“stateyear”变量:

d$stateyear <- as.numeric(factor(d$year))

标签: r

解决方案


像这样?

library(tidyverse)

d %>% 
  group_by(state_geocode_id) %>% 
  #add a row counter and duplicate the state id
  mutate(row = row_number(), 
         state2 = state_geocode_id) %>% 
  #now spread by the duplicate state to get a column for each state
  spread(key = state2, value = row, fill = 0)

# A tibble: 12 x 6
# Groups:   state_geocode_id [4]
state_geocode_id year  `100` `101` `102` `103`
<chr>            <chr> <dbl> <dbl> <dbl> <dbl>
1 100              2000      1     0     0     0
2 100              2001      2     0     0     0
3 100              2002      3     0     0     0
4 101              2000      0     1     0     0
5 101              2001      0     2     0     0
6 101              2002      0     3     0     0
7 102              2000      0     0     1     0
8 102              2001      0     0     2     0
9 102              2002      0     0     3     0
10 103              2000      0     0     0     1
11 103              2001      0     0     0     2
12 103              2002      0     0     0     3

推荐阅读