我想确定在时间t期间在同一地点和同一个人执行的活动id。变量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")
我们用pivot_longer
将数据集重塑为'long'格式,方法是指定names_sep
在列名中的小写字母和数字之间拆分,然后按'id'、'grp'、summarise
if
分组,'t'和'wher'列的n_distinct
为1,然后返回't'或else
0的first
元素,并在通过计数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