gpt4 book ai didi

r - 如何标记每组年份之间变量值的第一次变化?

转载 作者:行者123 更新时间:2023-12-04 23:38:58 26 4
gpt4 key购买 nike

给定一个包含不同组的非常大的纵向数据集,我需要创建一个标志,指示每个组 ( code ) 年 ( year ) 之间某个变量 ( id ) 的第一次变化。 type同一 id-year 内的观察次数仅表示不同的组成员。

样本数据:

library(tidyverse)    
sample <- tibble(id = rep(1:3, each=6),
year = rep(2010:2012, 3, each=2),
type = (rep(1:2, 9)),
code = c("abc","abc","","","xyz","xyz", "","","lmn","","efg","efg","def","def","","klm","nop","nop"))

我需要的是标记对 code 的第一个更改在一个组内,在几年之间。第二次更改无关紧要。缺少代码( "" )可以被视为 NA但无论如何不应该影响 flag .以下是上面带有标志字段的标题:
# A tibble: 18 × 5
id year type code flag
<int> <int> <int> <chr> <dbl>
1 1 2010 1 abc 0
2 1 2010 2 abc 0
3 1 2011 1 0
4 1 2011 2 0
5 1 2012 1 xyz 1
6 1 2012 2 xyz 1
7 2 2010 1 0
8 2 2010 2 0
9 2 2011 1 lmn 0
10 2 2011 2 0
11 2 2012 1 efg 1
12 2 2012 2 efg 1
13 3 2010 1 def 0
14 3 2010 2 def 0
15 3 2011 1 1
16 3 2011 2 klm 1
17 3 2012 1 nop 1
18 3 2012 2 nop 1

我仍然有循环思维,我正在尝试使用矢量化 dplyr 来做我需要的事情。
任何投入将不胜感激!

编辑:感谢您指出 year 的重要性. id 是按年份排列的,因为这里的顺序很重要,而且所有 typesidyear需要有相同的标志。因此,在编辑的第 15 行中,e 代码是 ""这本身并不能保证改变,但因为在同一年第 16 行有一个新的 code ,两个观测值都需要将其代码更改为 1。

最佳答案

我们可以使用 data.table

library(data.table)
setDT(sample)[, flag :=0][code!="", flag := {rl <- rleid(code)-1; cummax(rl*(rl < 2)) }, id]
sample
# id year type code flag
# 1: 1 2010 1 abc 0
# 2: 1 2010 2 abc 0
# 3: 1 2011 1 0
# 4: 1 2011 2 0
# 5: 1 2012 1 xyz 1
# 6: 1 2012 2 xyz 1
# 7: 2 2010 1 0
# 8: 2 2010 2 0
# 9: 2 2011 1 lmn 0
#10: 2 2011 2 0
#11: 2 2012 1 efg 1
#12: 2 2012 2 efg 1
#13: 3 2010 1 def 0
#14: 3 2010 2 def 0
#15: 3 2011 1 klm 1
#16: 3 2011 2 klm 1
#17: 3 2012 1 nop 1
#18: 3 2012 2 nop 1

更新

如果我们还需要包括“年份”,
setDT(sample)[, flag :=0][code!="",  flag := {rl <- rleid(code, year)-1
cummax(rl*(rl < 2)) }, id]

关于r - 如何标记每组年份之间变量值的第一次变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43891166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com