簡體   English   中英

如何使用帶有多個參數的 mapply 復制函數來計算方法的功效?

[英]How to replicate a function using mapply with multiple arguments to calculate the power of a method?

我有獨立和依賴的數據集。 我想測試因變量和自變量之間所有可能的關系,並最終計算該方法的功效。

# dependent dataset
test_A <- data.frame(matrix(rnorm(100), nr=10, nc=10))
# independent dataset
test_B <- data.frame(matrix(sample(c(0,1,2), 500, replace = TRUE), nr=50, nc=10))
# Find all combination using dependent and independe datasets's variables
A_B_pair <- subset(expand.grid(c1=names(test_A), c2=names(test_B), 
                                    stringsAsFactors = FALSE))

# Main function to estimate the parameter and p-values 
test_function <- function(x,y){
  c1 <- test_A [[x]]
  c2 <- test_B[[y]]
  Data <- data.frame(1, XX=c1, YY=c2)
  
  model_lm <- lm(YY ~ XX, Data)
  est_lm <- as.numeric(model_lm$coefficients)[2]
  pvalue_lm <- as.numeric(summary(model_lm)$coeffi[,4][2])

  return(unlist(data.frame(lm.estimator = est_lm, lm.pvalue =pvalue_lm)))
}

# Using mapply  to get the all pairs estimators and p-values
output <- mapply(test_function, x=A_B_pair$c1, y=A_B_pair$c2)

# transpose the output
output.data <- data.frame(t(output))

# Put all the dependent and independent variables and their estimated values and p-values in a data frame.
output_final <- cbind(A_B_pair, output.data)

我的問題是我需要復制這個函數 100 次來檢查方法的能力並估計參數。 將使用以下命令計算功率:

power <- mean(output_final$lm.pvalue <= 0.05)

我怎樣才能做到這一點? 你能幫我解決這個問題嗎? 非常感謝您的努力和幫助。

你可以試試 -

main_fn <- function() {
  test_A <- data.frame(matrix(rnorm(100), nr=10, nc=10))
  # independent dataset
  test_B <- data.frame(matrix(sample(c(0,1,2), 500, replace = TRUE), nr=50, nc=10))
  # Find all combination using dependent and independe datasets's variables
  A_B_pair <- subset(expand.grid(c1=names(test_A), c2=names(test_B), 
                                 stringsAsFactors = FALSE))
  
  output <- mapply(function(x, y) test_function(test_A, test_B, x, y), 
                   A_B_pair$c1, A_B_pair$c2)
  output.data <- data.frame(t(output))
  output_final <- cbind(A_B_pair, output.data)
}

test_function <- function(test_A, test_B, x,y){
  c1 <- test_A[[x]]
  c2 <- test_B[[y]]
  Data <- data.frame(1, XX=c1, YY=c2)
  
  model_lm <- lm(YY ~ XX, Data)
  est_lm <- as.numeric(model_lm$coefficients)[2]
  pvalue_lm <- as.numeric(summary(model_lm)$coeffi[,4][2])
  
  return(unlist(data.frame(lm.estimator = est_lm, lm.pvalue =pvalue_lm)))
}

result <- do.call(rbind, replicate(100, main_fn(), simplify = FALSE))
power <- mean(result$lm.pvalue <= 0.05)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM