考虑一个Data
具有多个因子和多个数值连续变量的数据集。其中一些变量,比如slice_by_1
(使用“Male”、“Female”slice_by_2
类)和(使用“Sad”、“Neutral”、“Happy”类),用于将数据“切片”为子集。对于每个子集,Kruskal-Wallis 测试应该在变量 上运行length
,preasure
每个pulse
都由另一个称为 的因子变量分组compare_by
。R 中是否有一种快速的方法来完成这项任务并将计算出的 p 值放入矩阵中?
我使用dplyr
包来准备数据。
样本数据集:
library(dplyr)
set.seed(123)
Data <- tbl_df(
data.frame(
slice_by_1 = as.factor(rep(c("Male", "Female"), times = 120)),
slice_by_2 = as.factor(rep(c("Happy", "Neutral", "Sad"), each = 80)),
compare_by = as.factor(rep(c("blue", "green", "brown"), times = 80)),
length = c(sample(1:10, 120, replace=T), sample(5:12, 120, replace=T)),
pulse = runif(240, 60, 120),
preasure = c(rnorm(80,1,2),rnorm(80,1,2.1),rnorm(80,1,3))
)
) %>%
group_by(slice_by_1, slice_by_2)
我们来看数据:
Source: local data frame [240 x 6]
Groups: slice_by_1, slice_by_2
slice_by_1 slice_by_2 compare_by length pulse preasure
1 Male Happy blue 10 69.23376 0.508694601
2 Female Happy green 1 68.57866 -1.155632020
3 Male Happy brown 8 112.72132 0.007031799
4 Female Happy blue 3 116.61283 0.383769524
5 Male Happy green 7 110.06851 -0.717791526
6 Female Happy brown 8 117.62481 2.938658488
7 Male Happy blue 9 105.59749 0.735831389
8 Female Happy green 2 83.44101 3.881268679
9 Male Happy brown 5 101.48334 0.025572561
10 Female Happy blue 10 62.87331 -0.715108893
.. ... ... ... ... ... ...
所需输出的示例:
Data_subsets length preasure pulse
1 Male_Happy <p-value> <p-value> <p-value>
2 Female_Happy <p-value> <p-value> <p-value>
3 Male_Neutral <p-value> <p-value> <p-value>
4 Female_Neutral <p-value> <p-value> <p-value>
5 Male_Sad <p-value> <p-value> <p-value>
6 Female_Sad <p-value> <p-value> <p-value>