r - 用 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
解决方案
使用dplyr
and 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)
推荐阅读
- c - 如何在 .txt 文件中找到所有单词的首字母
- python - 用于保存由类的许多实例产生的数据的模式
- c++ - 如何重载运算符以在 operator[] 调用上调用 setter 函数?
- python - 替代 concat 在数据框中插入记录
- solr - 调优 solr ConcurrentMergeScheduler
- javascript - 如何在 Twitch 扩展商店中上传 Twitch 面板扩展?
- maven - 无法使用 Maven 构建具有 gRPC、Protobuf 和 BoringSSL 到 JAR 的工作 Java 应用程序
- java - 如何在 Jenkins 上为 Maven Java 构建设置默认时区?
- python - 如何在不使用布尔索引的情况下迭代熊猫系列
- django - 如果使用 Gunicorn 运行 Django,则“NoneType”对象没有属性“autodiscover_tasks”