我正在努力寻找一个 R 函数,将我的数据转换为“基线值的变化倍数”。基本上我有一个由 subject.id 和时间点组成的 data.frame,按具有多个物种值的处理分组,如下所示:
subject.id timepoint treatment Species1 Species2 Species3 SpeciesX
id1 baseline A 40 10 5 5
id1 2h A 41 12 5 6
id1 4h A 40 20 6 5
id2 baseline B 50 10 5 5
id2 2h B 100 20 5 6
id2 4h B 200 20 6 5
我需要这样的东西,保持相同的物种名称,但折叠变化:
subject.id timepoint treatment Species1 Species2 Species3 SpeciesX
id1 baseline A 1 1 1 1
id1 2h A 1.02 1.2 1 1.2
id1 4h A 1 2 1.2 1
id2 baseline B 1 1 1 1
id2 2h B 2 2 1 1.2
id2 4h B 4 2 1.2 1
library(dplyr)
df %>%
group_by(subject.id, treatment) %>%
mutate(across(starts_with("Species"), ~.x/.x[timepoint == "baseline"]))
# A tibble: 6 × 7
# Groups: subject.id, treatment [2]
subject.id timepoint treatment Species1 Species2 Species3 SpeciesX
<chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl>
1 id1 baseline A 1 1 1 1
2 id1 2h A 1.02 1.2 1 1.2
3 id1 4h A 1 2 1.2 1
4 id2 baseline B 1 1 1 1
5 id2 2h B 2 2 1 1.2
6 id2 4h B 4 2 1.2 1