我有 97M 行的长表。每行包含一个人所采取的行动的信息和该行动的时间戳,格式如下:
actions <- c("walk","sleep", "run","eat")
people <- c("John","Paul","Ringo","George")
timespan <- seq(1000,2000,1)
set.seed(28100)
df.in <- data.frame(who = sample(people, 10, replace=TRUE),
what = sample(actions, 10, replace=TRUE),
when = sample(timespan, 10, replace=TRUE))
df.in
# who what when
# 1 Paul eat 1834
# 2 Paul sleep 1295
# 3 Paul eat 1312
# 4 Ringo eat 1635
# 5 John sleep 1424
# 6 George run 1092
# 7 Paul walk 1849
# 8 John run 1854
# 9 George sleep 1036
# 10 Ringo walk 1823
每个动作都可以由一个人采取或不采取,并且可以以任何顺序采取行动。
我有兴趣总结我的数据集中的动作顺序。特别是对于每个人,我想找出首先、第二、第三和第四次采取的行动。如果多次采取行动,我只对第一次发生感兴趣。然后,如果有人跑、吃、吃、跑和睡觉,我有兴趣总结一下,比如run
, eat
, sleep
。
df.out <- data.frame(who = factor(character(), levels=people),
action1 = factor(character(), levels=actions),
action2 = factor(character(), levels=actions),
action3 = factor(character(), levels=actions),
action4 = factor(character(), levels=actions))
我可以通过 forloop 获得我想要的东西:
for (person in people) {
tmp <- subset(df.in, who==person)
tmp <- tmp[order(tmp$when),]
chrono_list <- unique(tmp$what)
df.out <- rbind(df.out, data.frame(who = person,
action1 = chrono_list[1],
action2 = chrono_list[2],
action3 = chrono_list[3],
action4 = chrono_list[4]))
}
df.out
# who action1 action2 action3 action4
# 1 John sleep run <NA> <NA>
# 2 Paul sleep eat walk <NA>
# 3 Ringo eat walk <NA> <NA>
# 4 George sleep run <NA> <NA>
是否也可以在没有循环的情况下以更有效的方式获得此结果?