如何在r中以日期为条件,根据另一个df制作新的df?

时间:2020-06-18 15:49:04

标签: r dplyr

我想根据时间分析列,但是我不知道如何解决这个问题。

我有一个包含所有客户会话的数据框,并希望分析客户使用的接触点的顺序。我为使用的接触点类型制作了假人(类型1至4),现在我想对该顺序进行一些分析。首先,我想看看首选的类型是否对我的DVD有影响。因此,我想使用新变量在客户端级别上创建df:First_type1,First_type2,First_type3和First_type4。

我的会话数据如下:

Client id       Date     Type1    Type2    Type 3    Type 4
    1           01/01      0        0        1         0
    1           02/01      0        1        0         0
    2           01/01      1        0        0         0
    2           02/01      0        0        0         1
    2           02/01      0        0        0         1
    3           01/01      0        0        0         1
    3           02/02      0        0        1         0
    4           01/01      0        1        0         0
    4           02/01      0        1        0         0
    4           03/01      1        0        0         0
    4           04/01      0        1        0         0

我想让Client输出看起来像这样:

Client id    First_type1    First_type2    First_type3    First_type4
    1             0              0              1         0
    2             1              0              0         0
    3             0              0              0         1
    4             0              1              0         0

我不知道如何处理此问题,因此希望有人可以帮助我。预先感谢。

2 个答案:

答案 0 :(得分:1)

一种考虑的方法是使用pivot_longer延长数据,过滤value为1的行,slice选择行,并pivot_wider扩展数据以达到所需的目的格式。所有这些都假定日期是按顺序排列的(不确定Date列的类型)。

library(tidyverse)

df %>%
  pivot_longer(cols = starts_with("Type")) %>%
  group_by(Client_id) %>%
  filter(value == 1) %>%
  slice(1) %>%
  pivot_wider(id_cols = Client_id, names_from = name, values_from = value, names_prefix = "First_", values_fill = list(value = 0))

输出

# A tibble: 4 x 5
# Groups:   Client_id [4]
  Client_id First_Type3 First_Type1 First_Type4 First_Type2
      <int>       <int>       <int>       <int>       <int>
1         1           1           0           0           0
2         2           0           1           0           0
3         3           0           0           1           0
4         4           0           0           0           1

答案 1 :(得分:0)

如果四个新列中只有一个为每个用户带有1,则最好进行后续分析以将数据结构化为具有列出所用第一种类型的单个列:

library(dplyr)
library(tidyr)

df %>% 
  pivot_longer(cols = 3:6) %>% 
  filter(value == 1) %>% 
  group_by(Clientid) %>% 
  filter(as.numeric(Date) == min(as.numeric(Date))) %>% 
  select(Date = Date, first_type = name)

#> # A tibble: 4 x 3
#> # Groups:   Clientid [4]
#>   Clientid Date  first_type
#>      <int> <fct> <chr>     
#> 1        1 01/01 Type3     
#> 2        2 01/01 Type1     
#> 3        3 01/01 Type4     
#> 4        4 01/01 Type2