【发布时间】:2019-02-20 05:39:26
【问题描述】:
我有兴趣将多个变量标准化为控制子组的各自平均值。
假设我有一个数据框,我在其中测量来自 3 个不同条件(对照、药物 1、药物 2)的两个变量(分数 1 和分数 2)。
df <- data.frame(Treatment=rep(c( "Control", "Drug 1",
"Drug 2"), each=6 ),
Score1=c(4,5,4,5,5,6,8,9,10,8,9,9,14,15,13,15,14,15),
Score2=c(1,2,1,2,3,3,8,8,9,9,8,8,14,14,15,12,14,15))
df
Treatment Score1 Score2
1 Control 4 1
2 Control 5 2
3 Control 4 1
4 Control 5 2
5 Control 5 3
6 Control 6 3
7 Drug 1 8 8
8 Drug 1 9 8
9 Drug 1 10 9
10 Drug 1 8 9
11 Drug 1 9 8
12 Drug 1 9 8
13 Drug 2 14 14
14 Drug 2 15 14
15 Drug 2 13 15
16 Drug 2 15 12
17 Drug 2 14 14
18 Drug 2 15 15
我想将每个分数标准化为对照组的平均值(针对该分数)。最终结果是:
df.normal <- df
x <- mean(df$Score1[df$Treatment=="Control"])
y <- mean(df$Score2[df$Treatment=="Control"])
df.normal$Score1_normalised <- df$Score1 / x
df.normal$Score2_normalised <- df$Score2 / y
df.normal
Treatment Score1 Score2 Score1_normalised Score2_normalised
1 Control 4 1 0.8275862 0.5
2 Control 5 2 1.0344828 1.0
3 Control 4 1 0.8275862 0.5
4 Control 5 2 1.0344828 1.0
5 Control 5 3 1.0344828 1.5
6 Control 6 3 1.2413793 1.5
7 Drug 1 8 8 1.6551724 4.0
8 Drug 1 9 8 1.8620690 4.0
9 Drug 1 10 9 2.0689655 4.5
10 Drug 1 8 9 1.6551724 4.5
11 Drug 1 9 8 1.8620690 4.0
12 Drug 1 9 8 1.8620690 4.0
13 Drug 2 14 14 2.8965517 7.0
14 Drug 2 15 14 3.1034483 7.0
15 Drug 2 13 15 2.6896552 7.5
16 Drug 2 15 12 3.1034483 6.0
17 Drug 2 14 14 2.8965517 7.0
18 Drug 2 15 15 3.1034483 7.5
我认为使用 dplyr 可以做到这一点,但我一直在努力开始,并且由于我有大约 20 个变量,我希望有一条捷径,而不是走很长的路。
任何帮助将不胜感激!
【问题讨论】:
-
20 个变量是指 20 个分数吗?这能解决问题吗?
mutate_at(df, vars(starts_with("Score")), funs("normalised" = . / mean(.[Treatment == "Control"])))