首页 > 解决方案 > 用 NA 重塑长而完整

问题描述

我需要重塑一个df,用缺失的年份完成它,并创建一个可变的跟踪状态变化。问题是缺少某些值,而我编写的代码对这些值进行了制动。

玩具示例:

library(data.table)
df <- data.frame(id=c(1,2),phase_1=c(1994,1994),phase_2=c(1996,1996),phase_3=c(1997,NA))
df1 = melt(df, 
         id.vars = "id",
         measure.vars = c("phase_1", "phase_2", "phase_3"),
         variable.name = "status",
         value.name = "year",
         na.rm = FALSE)
df2 <- df1 %>%  complete(id, year = full_seq(year, 1)) %>% 
  fill(status)

期望的

  id year   phase change
1  1 1994 phase_1      0
2  1 1995 phase_1      0
3  1 1996 phase_2      1
4  1 1997 phase_3      1
5  2 1994 phase_1      0
6  2 1995 phase_1      0
7  2 1996 phase_2      1
8  2 1997 phase_2      0

标签: rdata.tablereshapenamelt

解决方案


使用dplyrand tidyr,您还可以执行以下操作:

df %>%
 gather(phase, year, -id, na.rm = TRUE) %>%
 complete(id, year = full_seq(year, 1)) %>%
 fill(phase) %>%
 group_by(id) %>%
 mutate(change = as.numeric(phase != lag(phase, default = first(phase))))

     id  year phase   change
  <dbl> <dbl> <chr>    <dbl>
1     1  1994 phase_1      0
2     1  1995 phase_1      0
3     1  1996 phase_2      1
4     1  1997 phase_3      1
5     2  1994 phase_1      0
6     2  1995 phase_1      0
7     2  1996 phase_2      1
8     2  1997 phase_2      0

或者:

 df %>%
 gather(phase, year, -id, na.rm = TRUE) %>%
 complete(id, year = full_seq(year, 1)) %>%
 fill(phase) %>%
 group_by(id) %>%
 mutate(change = (phase != lag(phase, default = first(phase))) * 1)

推荐阅读