尝试这样的事情:
mydf <- data.frame(group = c("A", "A", "B", "B",
"C", "C", "C", "D",
"D", "E", "E"),
type = c("pre", "post", "pre",
"post", "pre", "post",
"post", "pre", "post",
"pre", "post"),
value = 1:11)
times <- with(mydf, ave(value, group, type, FUN = seq_along))
xtabs(value ~ group + interaction(type, times), mydf)
# interaction(type, times)
# group post.1 pre.1 post.2 pre.2
# A 2 1 0 0
# B 4 3 0 0
# C 6 5 7 0
# D 9 8 0 0
# E 11 10 0 0
或者:
times <- with(mydf, ave(value, group, type, FUN = seq_along))
mydf$timevar <- interaction(mydf$type, times)
reshape(mydf, direction = "wide", idvar = "group",
timevar="timevar", drop="type")
# group value.pre.1 value.post.1 value.post.2
# 1 A 1 2 NA
# 3 B 3 4 NA
# 5 C 5 6 7
# 8 D 8 9 NA
# 10 E 10 11 NA
在这两种解决方案中,关键是创建一个“时间”变量,该变量由“类型”和可以用ave
.
为了完整起见,这里dcast
来自“reshape2”:
times <- with(mydf, ave(value, group, type, FUN = seq_along))
library(reshape2)
dcast(mydf, group ~ type + times)
# group post_1 post_2 pre_1
# 1 A 2 NA 1
# 2 B 4 NA 3
# 3 C 6 7 5
# 4 D 9 NA 8
# 5 E 11 NA 10