我具有以下格式的数据框
id var1 val1 status1 var2 val2 status2 var3 val3 status3
123 a 12 false b 23 true c 34 true
在这里,我想遍历行的每一列,使变量的状态第一次出现为true并将其保存到新行。这是以上示例的预期输出。
有没有一种方法可以不使用2 for循环呢? (在一个循环中循环)。
id var1 val1 status1 var2 val2 status2 var3 val3 status3 firstOccured
123 a 12 false b 23 true c 34 true b
答案 0 :(得分:3)
在我看来,使用长格式的数据会更容易。所以首先是要从宽变长
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))