0

我有一个数据框A,我将其拆分为 100 个数据框的列表,每个数据框有 3 行(在我的真实数据中,每个数据框有 500 行)。在这里,我展示了带有 2 个列表元素的 A(row1-row3;row4-row6):

A <- data.frame(n = c(0, 1, 2, 0, 1, 2),
                prob = c(0.4, 0.5, 0.1, 0.4, 0.5, 0.1),
                count = c(24878, 33605, 12100 , 25899, 34777, 13765))

# This is the list:
nest <- split(A, rep(1:2, each = 3))

我想对这些数据帧中的每一个应用多项测试并提取每个测试的 p 值。到目前为止,我已经这样做了:

library(EMT)

fun <- function(x){
  multinomial.test(x$count,
                   prob=x$prob,
                   useChisq = FALSE, MonteCarlo = TRUE,
                   ntrial = 100, # n of withdrawals accomplished
                   atOnce=100)
}

lapply(nest, fun)

但是,我得到:

 "Error in multinomial.test(x$counts_set, prob = x$norm_genome, useChisq = F,  : 
   Observations have to be stored in a vector, e.g.  'observed <- c(5,2,1)'"

有没有人有更聪明的方法来做到这一点?

4

2 回答 2

1

的结果split是用名称创建的12依此类推。这就是为什么x$countinfun无法访问它的原因。为了使其更简单,您可以使用该list函数组合拆分的元素,然后使用lapply

n <- c(0,1,2,0,1,2)
prob <- c(0.4, 0.5, 0.1, 0.4, 0.5, 0.1)
count <- c(24878, 33605, 12100 , 25899, 34777, 13765)
A <- cbind.data.frame(n, prob, count)

nest = split(A,rep(1:2,each=3))

fun <- function(x){
  multinomial.test(x$count,
                   prob=x$prob,
                   useChisq = F, MonteCarlo = TRUE,
                   ntrial = 100, # n of withdrawals accomplished
                   atOnce=100)
}

# Create a list of splitted elements
new_list <- list(nest$`1`, nest$`2`)

lapply(new_list, fun)
于 2018-11-10T05:10:18.377 回答
1

使用 dplyr 的解决方案。

A = data.frame(n = c(0,1,2,0,1,2),
               prob = c(0.4, 0.5, 0.1, 0.4, 0.5, 0.1),
               count = c(43, 42, 9, 74, 82, 9))

library(dplyr)
nest <- A %>%
  mutate(pattern = rep(1:2,each=3)) %>%
  group_by(pattern) %>%
  dplyr::summarize(mn_pvals = multinomial.test(count, prob)$p.value)
nest
于 2018-11-10T06:58:15.143 回答