【发布时间】:2020-07-09 01:57:50
【问题描述】:
我猜我看不到树林中的森林......因此,我想寻求帮助。
数据: dput() 输出见问题末尾。
-Dataframe dfA with the columns: ID; ts. ts being POSIXct -Dataframe dfB with the columns: ID; start; end; state_id. ID (corresponding to the ID in dfA), start (POSIXct), end (POSIXct), state_id.
任务:
我想根据条件在 dfA 中创建一个值为 1/0 的新列。 words 中的条件:如果 dfA 和 dfB 中的 ID 匹配,并且时间戳 dfA$ts 介于或等于 dfB$start 和 dfB$end 之间,则值 1 应写入 dfA$x,否则为 0应该在那里。
我认为代码应该看起来像这样:
dfA$x <- iflese( dfA$ID == dfB$ID & dfA$ts >= dfB$start & dfA$ts <= dfB$end, 1, 0)
提前感谢您的帮助。
输入(dfB):
结构(列表(ID = c(1151L, 1151L, 1150L, 1150L, 1150L, 1150L, 1152L,1152L,1152L,1345L),开始=结构(c(1443142500, 1443144600, 1442934900, 1442942400, 1442944800, 1442946300, 1443103500, 1443132600, 1443137400, 1443389400), class= c("POSIXct", "POSIXt" )), 结束 = 结构(c(1443143400, 1443145500, 1442935500, 1442943000, 1442945400, 1442950200, 1443106200, 1443134100, 1443140100, 1443392400 ), class= c("POSIXct", "POSIXt")), state_id = c(1L, 2L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 1L)), row.names = c(NA, -10L), class= "data.frame")
输入(dfA):
结构(列表(ID = c(1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1151L, 1150L, 1150L, 1150L, 1150L, 1150L, 1150L, 1150L, 1150L, 1150L, 1150L, 1150L, 1150L, 1152L, 1152L, 1152L, 1152L, 1152L, 1152L, 1152L, 1152L, 1152L, 1152L, 1152L, 1152L, 1152L, 1152L, 1152L, 1152L, 1345L, 1345L, 1345L, 1345L, 1345L, 1345L, 1345L, 1345L, 1345L, 1345L), ts = 结构(c(1443141300, 1443141600, 1443141900, 1443142200, 1443142500, 1443142800, 1443143100, 1443143400, 1443143700, 1443144000, 1443144300, 1443144600, 1443144900, 1443145200, 1443145500, 1443145800, 1443146100, 1443146400, 1443146700, 1443147000, 1442934900, 1442935200, 1442935500, 1442935800, 1442936100, 1442936400, 1442936700, 1442937000, 1442937300, 1442937600, 1442937900, 1442938200, 1443103500, 1443103800, 1443104100, 1443104400, 1443104700, 1443105000, 1443105300, 1443105600, 1443105900, 1443106200, 1443106500, 1443106800, 1443107100, 1443107400, 1443107700, 1443108000, 1443369300, 1443369600, 1443369900, 1443370200, 1443370500, 1443370800, 1443371100, 1443371400, 1443371700, 1443372000), class= c("POSIXct", "POSIXt" ))), row.names = c(NA, -58L), class= "data.frame")
【问题讨论】:
标签: r dataframe multiple-conditions