我有一个数据框,其中包含两个数值变量 fatcontent 和 saltcontent 以及两个描述不同处理方法的因子变量 cond 和 spice。在此数据框中,对数值变量的每次测量都进行了两次。
a <- data.frame(cond = rep(c("uncooked", "fried", "steamed", "baked", "grilled"),
each = 2, times = 3),
spice = rep(c("none", "chilli", "basil"), each = 10),
fatcontent = c(4, 5, 6828, 7530, 6910, 7132, 5885, 613, 2845, 2867,
25, 18, 2385, 33227, 4233, 4023, 953, 1025, 4465, 5016,
5, 5, 10235, 12545, 5511, 5111, 596, 585, 4012, 3633),
saltcontent = c(2, 5, 4733, 5500, 5724, 15885, 14885, 217, 193, 148,
6, 4, 26738, 24738, 22738, 23738, 267, 256, 1121, 1558,
1, 1, 21738, 20738, 26738, 27738, 195, 202, 129, 131)
)
现在,我希望将每个香料组的数值变量归一化(在这种情况下意味着除以未煮过的条件的平均值)。
例如。 $spice == "none"
cond spice fatcontent saltcontent
1 uncooked none 4 2
2 uncooked none 5 5
3 fried none 6828 4733
4 fried none 7530 5500
5 steamed none 6910 5724
6 steamed none 7132 15885
7 baked none 5885 14885
8 baked none 613 217
9 grilled none 2845 193
10 grilled none 2867 148
归一化后:
cond spice fatcontent saltcontent
1 uncooked none 0.8888889 0.5714286
2 uncooked none 1.1111111 1.4285714
3 fried none 1517.3333333 1352.2857143
4 fried none 1673.3333333 1571.4285714
5 steamed none 1535.5555556 1635.4285714
6 steamed none 1584.8888889 4538.5714286
7 baked none 1307.7777778 4252.8571429
8 baked none 136.2222222 62.0000000
9 grilled none 632.2222222 55.1428571
10 grilled none 637.1111111 42.2857143
我的问题是如何对数据框中的所有组和变量执行此操作?我假设我可以使用 dplyr 包,但我不确定什么是最好的方法。我感谢任何帮助!
最佳答案
我认为这就是你所追求的。您想使用未煮过的数据点找到每种香料条件的平均值。这是我在第一步中所做的事情。然后,我想将 fatmean
中的 saltmean
和 ana
添加到您的数据框 a
中。如果您的数据真的很大,这可能不是一种内存高效的方式。但是,我使用 left_join
来合并 ana
和 a
。然后,我在 mutate
中为每种香料条件进行了划分。最后,我删除了两列以使用 select
整理结果。
### Find mean for each spice condition using uncooked data points
ana <- group_by(filter(a, cond == "uncooked"), spice) %>%
summarise(fatmean = mean(fatcontent), saltmean = mean(saltcontent))
# spice fatmean saltmean
#1 basil 5.0 1.0
#2 chilli 21.5 5.0
#3 none 4.5 3.5
left_join(a, ana, by = "spice") %>%
group_by(spice) %>%
mutate(fatcontent = fatcontent / fatmean,
saltcontent = saltcontent / saltmean) %>%
select(-c(fatmean, saltmean))
# A part of the results
# cond spice fatcontent saltcontent
#1 uncooked none 0.8888889 0.5714286
#2 uncooked none 1.1111111 1.4285714
#3 fried none 1517.3333333 1352.2857143
#4 fried none 1673.3333333 1571.4285714
#5 steamed none 1535.5555556 1635.4285714
#6 steamed none 1584.8888889 4538.5714286
#7 baked none 1307.7777778 4252.8571429
#8 baked none 136.2222222 62.0000000
#9 grilled none 632.2222222 55.1428571
#10 grilled none 637.1111111 42.2857143
如果你在一个管道中做所有事情,它会是这样的:
group_by(filter(a, cond == "uncooked"), spice) %>%
summarise(fatmean = mean(fatcontent), saltmean = mean(saltcontent)) %>%
left_join(a, ., by = "spice") %>% #right_join is possible with the dev dplyr
group_by(spice) %>%
mutate(fatcontent = fatcontent / fatmean,
saltcontent = saltcontent / saltmean) %>%
select(-c(fatmean, saltmean))
关于r - 如何从 R 中的分组数据框中标准化子组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27435453/