我有下面的数据框,并尝试计算每个类别中各组之间的比例是否存在显着差异。例如。类别A组1对2、1对3和2对3。
是否有一种方法可以将p值作为新列计算并添加到数据帧中,而不必计算并一次手动添加一行?
或者是否有一种方法可以计算它们并将它们存储在单独的数据框中?
Group Category number min total Proportion
1 1 A 6 2.5 33 0.1818182
2 1 B 4 3.2 33 0.1212121
3 1 C 16 3.2 33 0.4848485
4 1 D 7 3.1 33 0.2121212
5 2 A 22 6.4 133 0.1654135
6 2 B 17 6.7 133 0.1278195
7 2 C 56 6.0 133 0.4210526
8 2 D 38 6.4 133 0.2857143
9 3 A 3 10.0 22 0.1363636
10 3 B 3 9.7 22 0.1363636
11 3 C 9 10.6 22 0.4090909
12 3 D 7 9.9 22 0.3181818
尽管解决方案看起来很容易,但解决方案相当复杂。这是使用purrr
软件包作为核心工具的解决方案。
让我们导入数据:
data <- structure(list(Group = c(1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L,
3L, 3L), Category = c("B", "C", "D", "A", "B", "C", "D", "A",
"B", "C", "D"), number = c(4L, 16L, 7L, 22L, 17L, 56L, 38L, 3L,
3L, 9L, 7L), min = c(3.2, 3.2, 3.1, 6.4, 6.7, 6, 6.4, 10, 9.7,
10.6, 9.9), total = c(33L, 33L, 33L, 133L, 133L, 133L, 133L,
22L, 22L, 22L, 22L), Proportion = c(0.1212121, 0.4848485, 0.2121212,
0.1654135, 0.1278195, 0.4210526, 0.2857143, 0.1363636, 0.1363636,
0.4090909, 0.3181818)), row.names = 2:12, class = "data.frame")
和必需的软件包:
library(dplyr) # mutate, group_by and rowwise functions
library(tidyr) # nest
library(purrr) # map
library(combinat) # combn
我们将创建tibble
对象foo
,该对象将按组划分原始数据集。这使我们能够将功能映射到组。
foo <- foo %>% mutate(tab = map(data, combFun))
现在我们定义自己的函数combPval
,其中1)创建一个因子组合(combTab
)的data.frame,2)创建data.frame tab1
,其中存储了prop.test
的相关列。这些data.frame在后续步骤中合并以创建data.frame data
。然后以prop.test
的方式应用rowwise
。
combPval <- function(group){
combTab <- combn(unique(group$Category), 2) %>% t() %>% data.frame()
tab1 <- group %>% select(Category, number, total)
combTab
temp <- merge(y=combTab, x=tab1, by.y="X2", by.x="Category" )
data <- merge(y=temp, x=tab1, by.y="X1", by.x="Category")
data <- data %>%
rowwise() %>%
mutate(
pval = prop.test(x=c(number.x, number.y), n=c(total.x, total.y))$p.val
)
data
}
以下列方式应用功能combPval
:
foo <- foo %>% mutate(results = map(data, combPval))
可以得到第一组的结果:
foo$results[[1]]
# A tibble: 3 x 7
# Rowwise:
Category number.x total.x Category.y number.y total.y pval
<chr> <int> <int> <chr> <int> <int> <dbl>
1 B 4 33 C 16 33 0.00322
2 B 4 33 D 7 33 0.509
3 C 16 33 D 7 33 0.0388