r - 如何按组设置时间为零?
问题描述
如果我有一个数据框有很多这样的行:
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”将时间设置为零?我想为该组的每个实例减去第一次。像这样:
subject-id activity label timestamp x y z
1 1600 A 0 -0.3647613 8.793503 1.0550842
2 1600 A .050354 -0.8797302 9.768784 1.0169983
3 1600 A .100708 2.0014954 11.109070 2.619156
4 1600 A .151062 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 .049355 -3.93443300 17.5387880 2.1100159
993 1600 B .100601 -0.08773804 12.7915650 -1.4541016
注意:我为活动 B 编了一些数字来说明我的意思。
我尝试过的:我尝试制作一个函数并将该函数与聚合一起应用:
time_zero <- function(vec){
result <- (vec$timestamp - vec$timestamp[1])/10E8
return(result)
}
test <- aggregate(pa, list(pa$`activity label`), FUN = time_zero)
解决方案
我们可以ave
在这里使用:
df$timestamp <- with(df, ave(timestamp, label, FUN = function(x) (x - x[1])/10E8))
和dplyr
library(dplyr)
df %>%
group_by(label) %>%
mutate(timestamp = (timestamp - first(timestamp))/10E8)
或者data.table
library(data.table)
setDT(df)[, timestamp := (timestamp - first(timestamp))/10E8, label]
这在每个除以 10E8时减去timestamp
with 。first
timestamp
label
推荐阅读
- kubernetes - K8s 无法使用 octavia 将浮动 ip 分配给负载均衡器
- android - 基于时间过滤器从 sqlite 获取数据
- scala - 当列名具有特殊字符(.点字符)时,df.na.fill 不起作用
- c++ - 在操作系统中一次可以打开多少个 SQLite DB 文件?
- mysql - MySQL - 计数器查询
- java - org.mockito.exceptions.verification.WantedButNotInvoked:
- node.js - 当我有 2 个名称相似的条目时出现错误
- azure-bot-service - Skype Bot ID、Microsoft App ID 和 Microsoft Azure Bot Service 之间是否存在依赖关系?
- git - 关于拉取请求的 Github 流程
- pyspark - PySpark - ValueError:无法将列转换为布尔值