gpt4 book ai didi

r - 完成序列列并填写行

转载 作者:行者123 更新时间:2023-12-05 02:41:08 26 4
gpt4 key购买 nike

我从一个数据集开始,该数据集具有数字列(在我的例子中是时间,但采用数字格式)、时间戳的特定事件和 ID。我希望运行一些代码来扩展数据框以填充数字序列,同时复制事件列(和任何其他相关列)。我想通过 ID 运行它,所以我不会填补 ID 之间的空白。

这是我开始使用的数据的一个简化示例。我想分别为每个 ID 填充“值”列的序列,用每个“事件”的第一行中的数据完成每个新行。

 a<-c("162", "164", "169", "171", "174", "188", "191", "198","200")
b<-c("start1","end1","start2", "event", "end2", "start1", "end1", "start2", "end2")
c<-c("A","A","A", "A", "A", "B", "B", "B", "B")

original<-data.table(value = a, event = b, ID = c)

这是我最终目标的重构:

agoal<-c(seq(from = 162, to = 174), seq(from = 188, to = 200))
bgoal<-c("start1","start1","end1","end1", "end1", "end1", "end1",
"start2", "start2", "event", "end2","end2", "end2",
"start1", "start1", "start1", "end1", "end1", "end1", "end1", "end1", "end1", "end1",
"start2", "start2","end2")
cgoal<-c(rep("A",13), rep("B",13))

goal<-data.table(value = agoal, event = bgoal, ID = cgoal)

抱歉,如果这不是很清楚!

最佳答案

我们可以使用 tidyr 包中的 completefill:首先使用tpye.convert(as.is=TRUE)将numeric赋给value

library(dplyr)
library(tidyr)

original %>%
type.convert(as.is=TRUE) %>%
group_by(ID) %>%
complete(value = first(value):max(value)) %>%
fill(event)

输出:

    value  event ID
1: 162 start1 A
2: 163 start1 A
3: 164 end1 A
4: 165 end1 A
5: 166 end1 A
6: 167 end1 A
7: 168 end1 A
8: 169 start2 A
9: 170 start2 A
10: 171 event A
11: 172 end2 A
12: 173 end2 A
13: 174 end2 A
14: 188 start1 B
15: 189 start1 B
16: 190 start1 B
17: 191 end1 B
18: 192 end1 B
19: 193 end1 B
20: 194 end1 B
21: 195 end1 B
22: 196 end1 B
23: 197 end1 B
24: 198 start2 B
25: 199 start2 B
26: 200 end2 B

关于r - 完成序列列并填写行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68239196/

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