如果我有一个包含许多行的数据框,如下所示:
subject-id activity label timestamp x y z
1 1600 A 2.522077e+14 -0.3647613 8.793503 1.0550842
2 1600 A 2.522077e+14 -0.8797302 9.768784 1.0169983
3 1600 A 2.522078e+14 2.0014954 11.109070 2.619156
4 1600 A 2.522078e+14 0.4506226 12.651642 0.18455505
5 1600 A 2.522079e+14 -2.1643524 13.928436 -4.4224854
6 1600 A 2.522079e+14 -4.3327790 13.361191 -0.7188721
.
.
.
subject-id activity label timestamp x y z
991 1600 B 2.519876e+14 1.37554930 15.3750460 2.9716187
992 1600 B 2.519877e+14 -3.93443300 17.5387880 2.1100159
993 1600 B 2.519877e+14 -0.08773804 12.7915650 -1.4541016
994 1600 B 2.519878e+14 2.03874200 3.0771484 -1.0537262
995 1600 B 2.519878e+14 -2.55847170 -2.7386780 -2.0985107
996 1600 B 2.519879e+14 -1.35530090 0.3884125 -0.6598511
.
.
.
subject-id activity label timestamp x y z
24551 1601 A 12865.64 4.7034090 9.127296 0.06404489
24552 1601 A 12865.68 5.3546320 15.635334 -0.62907650
24553 1601 A 12865.72 6.3997010 12.926893 0.45010993
24554 1601 A 12865.76 10.5320930 13.207614 -1.02471830
24555 1601 A 12865.80 16.1297360 2.683301 1.14263270
24556 1601 A 12865.84 0.3932476 6.549937 -3.78224020
如何将“主题 ID”和“事件标签”组的时间设置为零,然后在向下移动行时将组的其余部分递增 0.05。像这样:
subject-id activity label timestamp x y z
1 1600 A 0 -0.3647613 8.793503 1.0550842
2 1600 A .05 -0.8797302 9.768784 1.0169983
3 1600 A .10 2.0014954 11.109070 2.619156
4 1600 A .15 0.4506226 12.651642 0.18455505
.
.
.
subject-id activity label timestamp x y z
991 1600 B 0 1.37554930 15.3750460 2.9716187
992 1600 B .05 -3.93443300 17.5387880 2.1100159
993 1600 B .10 -0.08773804 12.7915650 -1.4541016
.
.
.
subject-id activity label timestamp x y z
24551 1601 A 0 4.7034090 9.127296 0.06404489
24552 1601 A .05 5.3546320 15.635334 -0.62907650
24553 1601 A .10 6.3997010 12.926893 0.45010993
我一直在尝试使用 dplyr 函数,因为从长远来看,我在循环方面往往会失败。我已经尝试过以下操作,但我无法弄清楚 mutate 的参数应该是什么:
test <- as.data.frame(df %>% group_by(`activity label`, `subject-id`) %>% mutate(timestamp = ???))
我不应该使用 mutate() 吗?我应该使用 do() 吗?
最佳答案
我们可以使用seq
创建从0开始的序列,步长为0.05,长度为每组中的行数。
library(dplyr)
df %>%
group_by(`activity label`, `subject-id`) %>%
mutate(timestamp = seq(0, by = 0.05, length.out = n()))
n()
给出行数,因为我们的数据在这里分组,所以它给出了每组中的行数。
关于r - 如何根据两个不同的组重写列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60313419/