首页 > 解决方案 > 如何收集列和一对成对的列?

问题描述

第一次来这里。希望你能帮忙。请让我知道 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"))

文字解释

我采访了一些人并收集了关于

问题 我想从宽到长。但是,我只想要关于它们是否更改的数据,以及将其添加到“索引”行而不是“预索引”行的原因。它应该如下所示:

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

希望你能帮忙

体重

标签: rtidyr

解决方案


您可以获取长格式数据pivot_longer并使用列名中的模式来获取单独列中的数据,以便choice_preindexchoice_index的值在 1 列中,start_preindexstart_index的值在一列中,依此类推。对于每个,record_id您可以将replace的第一个值change_yn和列添加到。final_choicereason_changeNA

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

推荐阅读