在我看来,使用长格式数据会更容易。所以首先是从宽到长重塑
dat_long <- reshape(dat, idvar = "id", varying = 2:ncol(dat), direction = "long", sep = "")
假设您有多个id,您可以使用ave(用于分组)和match(获取"true"在status中的第一个索引)如下:
dat_long <- transform(dat_long,
firstOccured = ave(status, id, FUN = function(x) var[match("true", x)]))
结果
dat_long
# id time var val status firstOccured
#123.1 123 1 a 12 false b
#123.2 123 2 b 23 true b
#123.3 123 3 c 34 true b
如果我们需要回到宽幅格式,我们可以这样做
out <- reshape(dat_long, idvar = "id", timevar = "time", direction = "wide", sep = "")
out <- out[setdiff(names(out), c("firstOccured1", "firstOccured2"))]
out
# id var1 val1 status1 var2 val2 status2 var3 val3 status3 firstOccured3
#123.1 123 a 12 false b 23 true c 34 true b
数据
dat <- structure(list(id = 123L, var1 = "a", val1 = 12L, status1 = "false",
var2 = "b", val2 = 23L, status2 = "true", var3 = "c", val3 = 34L,
status3 = "true"), .Names = c("id", "var1", "val1", "status1",
"var2", "val2", "status2", "var3", "val3", "status3"), class = "data.frame", row.names = c(NA,
-1L))