首页 > 解决方案 > 对数据表进行排序后,我可以选择一个值,取消排序,然后将该值及其下方的 5 个值保存到数据框中吗?

问题描述

在上一个问题中,我问了如何找到滚动均值,谢谢您的帮助!

然而,既然我的滚动平均值的代谢值最低,我的桌子就不再有序了。我想标记该行中的 O2 值,将其重新排序到其原始位置,然后将该 02 值与它下面的下 4 个值取平均值。这可能吗?

我只是不确定如何设置标志让 R 知道我想在对表格进行排序后继续使用这个值

或者,与其取消排序和标记我指定的 O2 值,不如只标记该 O2 值的时间戳,在原始工作表中找到该时间,然后从该行中选择 O2 以对 5 个值进行平均在它下面?

我希望得到的值是从 13:36 到 14:01 的平均 V02 值,即:0.738622117

Date       Time     kCal       VO2      VCO2      Lowest Average    
2020/08/11 13:36:00 0.1796796 0.6212131 0.5481290 1.290649
2020/08/11 13:41:00 0.1796833 0.6212261 0.5481405 1.412320
2020/08/11 18:06:00 0.2475342 0.8529993 0.7080062 1.540823
2020/08/11 13:46:00 0.1796903 0.6212505 0.5481620 1.551518
2020/08/11 18:01:00 0.3073857 1.0778390 0.9221587 1.580908
etc.

编辑:从第二个解决方案:

> August11RMR6[,..I:=.I]

> setorder(August11RMR6, VO2_M_1, na.last=T)

> August11RMR6[..I%in%(..I[1]+(0:4)),]

输出:

              DateTime kcal_hr_M_1   VO2_M_1  VCO2_M_1 Sum_6period ..I
1: 2020/08/11 13:36:00   0.1796796 0.6212131 0.5481290    1.290649   1
2: 2020/08/11 13:41:00   0.1796833 0.6212261 0.5481405    1.412320   2
3: 2020/08/11 13:46:00   0.1796903 0.6212505 0.5481620    1.551518   4
4: 2020/08/11 18:06:00   0.2475342 0.8529993 0.7080062    1.540823   3
5: 2020/08/11 18:01:00   0.3073857 1.0778390 0.9221587    1.580908   5

从第一个解决方案:

> August11RMR6[,..I:=.I]

> row.num <- as.numeric(August11RMR6[order(VO2_M_1)[1], "..I"])

> row.num
[1] 1

> August11RMR6[row.num+(0:4)]

标签: r

解决方案


# save the actual row numbers to a new column
dfs[,..I:=.I]
# get the row number of the smallest value
row.num <- as.numeric(dfs[order(VO2_M_1)[1], "..I"])
row.num
[1] 1
# get the 4 values that follow the smallest one
dfs[row.num+(0:4)]
#>               DateTime kcal_hr_M_1   VO2_M_1  VCO2_M_1  roll_sum ..I
#> 1: 2020/08/11 13:36:00   0.1796796 0.6212131 0.5481290 0.9647027   1
#> 2: 2020/08/11 13:41:00   0.1796833 0.6212261 0.5481405 1.1109694   2
#> 3: 2020/08/11 13:46:00   0.1796903 0.6212505 0.5481620 1.2326371   3
#> 4: 2020/08/11 13:51:00   0.1797111 0.6213223 0.5482253 1.3718277   4
#> 5: 2020/08/11 13:56:00   0.2459384 0.8402357 0.7533433 1.5177674   5

编辑

# save the actual row numbers to a new column
dfs[, ..I:=.I]
# set the order of the data.table
setorder(dfs, VO2_M_1, na.last=T)
# get the 4 values that follow the smallest one
dfs[..I%in%(..I[1]+(0:4)),]
#>               DateTime kcal_hr_M_1   VO2_M_1  VCO2_M_1  roll_sum ..I
#> 1: 2020/08/11 13:36:00   0.1796796 0.6212131 0.5481290 0.9647027   1
#> 2: 2020/08/11 13:41:00   0.1796833 0.6212261 0.5481405 1.1109694   2
#> 3: 2020/08/11 13:46:00   0.1796903 0.6212505 0.5481620 1.2326371   3
#> 4: 2020/08/11 13:51:00   0.1797111 0.6213223 0.5482253 1.3718277   4
#> 5: 2020/08/11 13:56:00   0.2459384 0.8402357 0.7533433 1.5177674   5

推荐阅读