gpt4 book ai didi

r - data.table 在新列中粘贴值的方法以另一列中的值为条件

转载 作者:行者123 更新时间:2023-12-05 02:19:37 24 4
gpt4 key购买 nike

有人可以建议怎么做吗?我有这个数据:

ty<-data.table(id=c(1,1,1,2,2,3,3,4,4,5,5),
date=c("11-23-2015","06-22-2015","07-22-2016","03-03-2012","11-08-2015","11-10-2012","11-23-2015","11-12-2012","12-02-2015","08-24-2016","12-25-2008"),
event=c("open","gt","gf","gf","open","ff","open","open","close","tr","ww"))
ty$date<-as.Date(ty$date,format="%m-%d-%Y")

id date event
1: 1 2015-11-23 open
2: 1 2015-06-22 gt
3: 1 2016-07-22 gf
4: 2 2012-03-03 gf
5: 2 2015-11-08 open
6: 3 2012-11-10 ff
7: 3 2015-11-23 open
8: 4 2012-11-12 open
9: 4 2015-12-02 close
10: 5 2016-08-24 tr
11: 5 2008-12-25 ww

我需要提取与事件“打开”相对应的日期并将其粘贴到按 id 索引的第四列中,如以下示例所示:

        id       date event open_date
1: 1 2015-11-23 open 2015-11-23
2: 1 2015-06-22 gt 2015-11-23
3: 1 2016-07-22 gf 2015-11-23
4: 2 2012-03-03 gf 2015-11-08
5: 2 2015-11-08 open 2015-11-08
6: 3 2012-11-10 ff 2015-11-23
7: 3 2015-11-23 open 2015-11-23
8: 4 2012-11-12 open 2012-11-12
9: 4 2015-12-02 close 2012-11-12
10: 5 2016-08-24 tr NA
11: 5 2008-12-25 ww NA

我用过这个:

ty[, open_date := if (event == "open") paste(date), by=id]

但它只在引用行中粘贴日期,而我需要在所有 id 行中粘贴日期。可能不是最佳的,但这是我需要的。感谢和问候

最佳答案

将@Sotos 和@DavidArenburg 在社区维基答案中的评论中提供的解决方案转换:

# @Sotos' solution
ty[, open_date := date[event == 'open'], by = id]
# @DavidArenburg's solution:
ty[ty[event == "open"], open_date := i.date, on = .(id)]

两种方案的结果:

#     id       date event  open_date
# 1: 1 2015-11-23 open 2015-11-23
# 2: 1 2015-06-22 gt 2015-11-23
# 3: 1 2016-07-22 gf 2015-11-23
# 4: 2 2012-03-03 gf 2015-11-08
# 5: 2 2015-11-08 open 2015-11-08
# 6: 3 2012-11-10 ff 2015-11-23
# 7: 3 2015-11-23 open 2015-11-23
# 8: 4 2012-11-12 open 2012-11-12
# 9: 4 2015-12-02 close 2012-11-12
# 10: 5 2016-08-24 tr <NA>
# 11: 5 2008-12-25 ww <NA>

关于r - data.table 在新列中粘贴值的方法以另一列中的值为条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42111429/

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