【问题标题】:Is there a function finding common time-steps?有没有找到共同时间步长的函数?
【发布时间】:2020-09-08 07:09:02
【问题描述】:

我想识别在时间 t 期间在同一地点和同一个人进行的活动。变量wher 表示时间步长并记录活动在时间 t 发生的位置。 with 参数记录在时间 t 与谁一起执行活动。我想知道在时间 t 基于 id 和 pnum 在同一地点和同一个人进行的活动的持续时间或总发生次数。不同的人在不同的地方进行的不寻常的活动和活动我用 0 代替。

输入

id     pnum     t1  t2  t3  t4  wher1 wher2 wher3 wher4 wit1 wit2 wit3 wit4  
12       1      12  12  12  12  1        1   1     4     8     9    4    0  
12       2      10  13  12  12  3        1   1     5     6     5    4    1
12       3      10  13  12  12  3        1   1     5     6     5    4    1

输出:

id  t1  t2  t3  t4 Occurance number 
12   0   0  12  0   3

样本数据:

 df<-structure(list(id = c(12, 12, 12), pnum = c(1, 2, 3), t1 = c(12, 10, 10), t2 = c(12, 13,13), t3 = c(12, 12,12), t4 = c(12, 12, 12), wher1 = c(1, 3, 3), 
wher2 = c(1,1,1), 
wher3= c(1, 1, 1), wher4 = c(4, 5,5), wit1 = c(8, 6,6), wit2 = c(9,5,5), wit3 = c(4,4,4), wit4 = c(0, 1,1)),  row.names = c(NA,3L), class = "data.frame")

【问题讨论】:

  • @akrun 感谢不常见的手段,例如有时在步骤 t4,即使有共同的活动,这些活动是在不同的地方(4 和 5 和 5)和不同的人(0-1-1)进行的.因此不常见。 Common 是 t3 有共同的活动,其中有共同的元素,而 wit3 也有共同的元素。

标签: r dataframe


【解决方案1】:

我们使用pivot_longer 将数据集重塑为“long”格式,方法是指定names_sep 在列名中的小写字母和数字之间进行拆分,然后按“id”、“grp”、summarise 分组if 't' 和 'wher' 列的n_distinct 为 1,然后返回 't' 的 first 元素或 else 0,并在创建 ' 的数量后重新整形回 'wide' 格式Occurance' 通过计算 0 的个数

library(dplyr)
library(tidyr)
library(stringr)
df %>% 
   pivot_longer(cols = t1:wit4, names_to = c(".value", "grp"), 
    names_sep = "(?<=[a-z])(?=[1-9])") %>% 
   group_by(id, grp) %>% 
   summarise(n = if(n_distinct(t) == 1 & n_distinct(wher)== 1) 
             first(t) else 0) %>%
   mutate(Occurance = sum(n == 0), grp = str_c('t', grp)) %>% 
   pivot_wider(names_from = grp, values_from = n)
# A tibble: 1 x 6
# Groups:   id [1]
#    id Occurance    t1    t2    t3    t4
#  <dbl>     <int> <dbl> <dbl> <dbl> <dbl>
#1    12         3     0     0    12     0

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 2013-02-17
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    相关资源
    最近更新 更多