r - 如何收集列和一对成对的列?
问题描述
第一次来这里。希望你能帮忙。请让我知道 reprex 的任何改进。
这是一个收集()问题。
数据
structure(list(record_id = 110001L, choice_preindex = 0L, start_preindex = structure(16622, class = "Date"),
stop_preindex = structure(16631, class = "Date"), change_yn = 1L,
choice_index = 3L, start_index = structure(16632, class = "Date"),
stop_index = structure(17354, class = "Date"), final_choice = 1L,
reason_change = 1L), row.names = c(NA, -1L), class = c("tbl_df",
"tbl", "data.frame"))
文字解释
我采访了一些人并收集了关于
- 他/她在会议之前使用了哪种产品,从什么时候到什么时候(choice_preindex、start_preindex、stop_preindex)
- 他/她在会后使用了哪种产品,从什么时候到什么时候(choice_index、start_index、stop_index)
- 会后他们是否换了,如果是,为什么?(change_yn,reason_change)
- 这是最后一次改变吗?(final_choice)暂时不重要
问题 我想从宽到长。但是,我只想要关于它们是否更改的数据,以及将其添加到“索引”行而不是“预索引”行的原因。它应该如下所示:
| record_id | choice | start | stop | change_yn | reason_change | final choice |
|-----------|--------|------------|------------|-----------|---------------|--------------|
| 110001 | 0 | 2015-07-06 | 2015-07-15 | N/A | N/A | N/A |
| 110001 | 3 | 2015-07-16 | 2017-07-07 | 1 | 1 | 1 |
希望你能帮忙
体重
解决方案
您可以获取长格式数据pivot_longer
并使用列名中的模式来获取单独列中的数据,以便choice_preindex
和choice_index
的值在 1 列中,start_preindex
和start_index
的值在一列中,依此类推。对于每个,record_id
您可以将replace
的第一个值change_yn
和列添加到。final_choice
reason_change
NA
library(dplyr)
df %>%
tidyr::pivot_longer(cols = ends_with('index'),
names_to = '.value',
names_pattern = '(.*)_.*') %>%
group_by(record_id) %>%
mutate(across(c(change_yn, final_choice, reason_change), replace, 1, NA))
# record_id change_yn final_choice reason_change choice start stop
# <int> <int> <int> <int> <int> <date> <date>
#1 110001 NA NA NA 0 2015-07-06 2015-07-15
#2 110001 1 1 1 3 2015-07-16 2017-07-07
推荐阅读
- java - 如何在不自动构建的情况下使 Eclipse 中的热代码替换工作?
- c# - 无法将 Texture2D Atlas 应用于材质
- java - 添加图像时,相同大小的图块的 JavaFX GridPane 无法保持正确的大小
- javascript - 等待一个函数在 GAS 中执行
- reactjs - 几次导航后反应路由器dom白屏
- javascript - Chrome:window.location.reload(true)-状态代码:200 OK(来自内存缓存)而不是来自服务器的新版本文件
- sql - SQL 查询 GROUP BY 在通过 Google Chome 访问的 w3 学校网站上未按预期工作,通过 Firefox 按预期工作
- angular - 两个组件监听同一个 observable
- html - Ng-options 不起作用,无论我尝试什么
- python - 定义中的 Python Var