我正在尝试计算一段时间内的体重减轻,因此初始体重非常重要。我想基于每个托盘在“天” = 0时的重量创建一列“初始重量”。示例如下:
Day Tray Weight Initial Weight
0 1 3303 3303
3 1 3302.4 3303
6 1 3303 3303
15 1 3295.3 3303
36 1 3281.2 3303
0 2 3428 3428
3 2 3426 3428
6 2 3425 3428
15 2 3422 3428
36 2 3417 3428
一旦有了初始的“体重”值,就可以在新列中计算出体重减轻:(初始体重-体重(t))/初始体重。
data.frame(
Day = c(0L, 3L, 6L, 15L, 36L, 0L, 3L, 6L, 15L, 36L),
Tray = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L),
Weight = c(3303, 3302.4, 3303, 3295.3, 3281.2, 3428, 3426, 3425, 3422, 3417)
)
答案 0 :(得分:0)
dplyr的实现方式
library(tidyverse)
data.frame(
Day = c(0L, 3L, 6L, 15L, 36L, 0L, 3L, 6L, 15L, 36L),
Tray = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L),
Weight = c(3303, 3302.4, 3303, 3295.3, 3281.2, 3428, 3426, 3425, 3422, 3417)
) %>%
mutate(inw = case_when(Day == 0 ~ Weight, TRUE ~ -99)) %>%
group_by(Tray) %>%
mutate(inw = max(inw)) %>%
mutate(loss = (inw-Weight) / inw)
结果
Day Tray Weight inw loss
<int> <int> <dbl> <dbl> <dbl>
1 0 1 3303 3303 0
2 3 1 3302.4 3303 0.000182
3 6 1 3303 3303 0
4 15 1 3295.3 3303 0.00233
5 36 1 3281.2 3303 0.00660
6 0 2 3428 3428 0
7 3 2 3426 3428 0.000583
8 6 2 3425 3428 0.000875
9 15 2 3422 3428 0.00175
10 36 2 3417 3428 0.00321
答案 1 :(得分:0)
这是基于R的方法
RUN node --max-old-space-size=8192 $(npm bin)/ng build --prod --aot --build-optimizer --no-progress
数据:
> df1$Initial_Weight <- unlist(lapply(split(df1, df1$Tray), function(x) rep(x$Weight[x$Day==0], nrow(x))))
> df1$Loss <- (df1$Initial_Weight-df1$Weight)/df1$Initial_Weight
> df1
Day Tray Weight Initial_Weight Loss
1 0 1 3303.0 3303 0.0000000000
2 3 1 3302.4 3303 0.0001816530
3 6 1 3303.0 3303 0.0000000000
4 15 1 3295.3 3303 0.0023312140
5 36 1 3281.2 3303 0.0066000606
6 0 2 3428.0 3428 0.0000000000
7 3 2 3426.0 3428 0.0005834306
8 6 2 3425.0 3428 0.0008751459
9 15 2 3422.0 3428 0.0017502917
10 36 2 3417.0 3428 0.0032088681
答案 2 :(得分:0)
下面是一个简单的基础R解决方案。
dat$Initial_Weight <- with(dat, ave(Weight, Tray, FUN = function(x) x[1]))
dat$Loss <- with(dat, (Initial_Weight - Weight)/Initial_Weight)
dat
# Day Tray Weight Initial_Weight Loss
#1 0 1 3303.0 3303 0.0000000000
#2 3 1 3302.4 3303 0.0001816530
#3 6 1 3303.0 3303 0.0000000000
#4 15 1 3295.3 3303 0.0023312140
#5 36 1 3281.2 3303 0.0066000606
#6 0 2 3428.0 3428 0.0000000000
#7 3 2 3426.0 3428 0.0005834306
#8 6 2 3425.0 3428 0.0008751459
#9 15 2 3422.0 3428 0.0017502917
#10 36 2 3417.0 3428 0.0032088681