为什么这有效:
est <- unlist(column) %>%
sample(i, replace = TRUE) %>%
matrix(nrow = B, ncol = i) # %>%
est <- switch(param,
"mean" = rowMeans2(est, na.rm = TRUE),
"sd" = rowSds(est, na.rm = TRUE),
stop("Invalid `param` value. Valid values are 'mean' or 'sd.'")
) # %>%
est <- mean(est)
但这并不:
est <- unlist(column) %>%
sample(i, replace = TRUE) %>%
matrix(nrow = B, ncol = i) %>%
switch(
param,
"mean" = rowMeans2(., na.rm = TRUE),
"sd" = rowSds(., na.rm = TRUE),
stop("Invalid `param` value. Valid values are 'mean' or 'sd.'")
) %>%
mean()
使用管道的示例给出以下错误:
switch(., param, Mean = rowMeans2(., na.rm = TRUE), sd = 中的错误 rowSds(., : EXPR 必须是长度为 1 的向量
还发现
case_when
使用管道失败:
case_when(
param == "mean" ~ rowMeans2(na.rm = TRUE),
param == "sd" ~ rowSds(na.rm = TRUE),
TRUE ~ (stop("Invalid `param` value. Valid values are 'mean' or 'sd.'"))
) %>%
mean()
有不同的错误:
错误:!情况 1 (case_when()
) 必须是双边公式, 不是双矩阵。.
# Sample data
set.seed(123)
column <- data.frame(X1 = rnorm(100))
# Parameters
i <- 5
B <- 100
param <- "mean"
# Load matrixStats
library(matrixStats)
# My function
myFunc <- function(i, column, B, param) {
est <- unlist(column) %>%
sample(i, replace = TRUE) %>%
matrix(nrow = B, ncol = i) %>%
switch(
param,
"mean" = rowMeans2(., na.rm = TRUE),
"sd" = rowSds(., na.rm = TRUE),
stop("Invalid `param` value. Valid values are 'mean' or 'sd.'")
) %>%
mean()
# Print the result
print(est)
}
# Call the function for testing
myFunc(i, column, B, param)
您在管道内调用
switch
,因此前一个参数将取代第一个参数 EXPR
。它不是标量,所以这是一个错误。您可以通过首先解析 param
轻松解决此问题,并且您也只需要执行一次:
myFunc <- function(i, column, B, param) {
## Parse once, outside pipeline
paramfunc <- switch(
param,
"mean" = \(x) rowMeans2(x, na.rm = TRUE),
"sd" = \(x) rowSds(x, na.rm = TRUE),
stop("Invalid `param` value. Valid values are 'mean' or 'sd.'")
)
## Insert above into pipeline
est <- unlist(column) %>%
sample(i, replace = TRUE) %>%
matrix(nrow = B, ncol = i) %>%
paramfunc() %>%
mean()
# Print the result
print(est)
}
myFunc(i, column, B, param)
#> 0.03787134