【发布时间】:2018-04-29 13:06:24
【问题描述】:
我正在处理一个数据框,其中包含三个标记为 id、time1 和 time2 的列。一个示例是:
df <-
structure(
list(
id = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L),
time1 = c(12L, 5L, 3L, 5L, 6L, 30L, 3L, 30L, 7L, 2L, 17L, 5L, 8L, 3L, 22L, 5L, 15L, 4L, 7L, 23L),
time2=c(23L,23L,23L,23L,23L,22L,22L,22L,22L,22L,25L,25L,25L,25L,25L,24L,24L,24L,24L,24L)
),
.Names = c("id", "time1","time2"),
class = "data.frame",
row.names = c(NA,-20L)
)
我正在使用 R,我正在尝试对这些数据进行子集化,并根据以下条件将列 time2 替换为新列:
将每个
id的time1的值求和,直到它大于或等于该id的time2的对应值。用每个
id的相应time2值替换time1中求和终止的单元格。time2列将替换为标记为status的新列,该列由0和1组成。也就是说,status对time1的未替换值和0的所有替换值time1采用1。
总之,我希望看到这样的结果:
df <-
structure(
list(
id = c(1L, 1L, 1L, 1L, 2L, 3L, 3L, 3L, 4L, 4L, 4L),
time1 = c(12L, 5L, 3L, 23, 22L, 17L, 5L, 25L, 5L, 15L, 24L),
status=c(1L,1L,1L,0L,0L,1L,1L,0L,1L,1L,0L)
),
.Names = c("id", "time1","status"),
class = "data.frame",
row.names = c(NA,-11L)
)
非常感谢您对此提供的任何帮助。
【问题讨论】:
标签: r