r - 使用 sapply() 在两个参数上循环 uniroot()

标签 r loops

此函数根据管道的直径、流量和长度计算管道中的压力损失。

hazwil2 <- function(diam, flow, leng){
  psi2=((1/(2.31*100))*1050*((flow/140)^1.852)*leng*diam^-4.87)
  return(psi2)
}

我正在寻找能够将压力损失保持在 2 psi 以内的最小直径。直径范围在 2 到 12 英寸之间。使用 uniroot() 和两个任意值的流量和长度:

intercept   = 2L
uniroot(
  function(x) hazwil2(x, 100, 400) - intercept ,
  interval = c(2, 12)
)$root

现在我尝试在这个流量和长度值数据集上循环 uniroot

data <- read.csv(
  text = 
  "leng,flow
  100, 100
  200, 100
  300, 100
  100, 150
  200, 150
  300, 150
  100, 200
  200, 200
  300, 200",
  stringsAsFactors = FALSE
)

最佳答案

考虑对 fl 参数泛化您的 unitroot 调用,并将其传递到 mapply(m多次应用)以按元素向下迭代等长向量(即数据帧的列、长度):

find_root <- function(f, l) {
  intercept <- 2L
  uniroot(
    function(x) hazwil2(x, f, l) - intercept ,
    interval = c(2, 12)
  )$root
}

data$root <- mapply(find_root, data$flow, data$leng)

data
#   leng flow     root
# 1  100  100 2.681145
# 2  200  100 3.091243
# 3  300  100 3.359606
# 4  100  150 3.128141
# 5  200  150 3.606602
# 6  300  150 3.919727
# 7  100  200 3.489780
# 8  200  200 4.023564
# 9  300  200 4.372916

对于可能产生根本问题的较大集合,考虑在 tryCatch 中包装函数调用以返回 NA:

data <- expand.grid(leng = seq(100, 1000, by=100), flow = seq(10, 200, by=10))
data$root <- mapply(function(l,f) tryCatch(find_root(l,f), error=function(e) NA), 
                    data$flow, data$leng)

输出

head(data, 20)

#    leng flow     root
# 1   100   10       NA
# 2   200   10       NA
# 3   300   10       NA
# 4   400   10       NA
# 5   500   10       NA
# 6   600   10       NA
# 7   700   10       NA
# 8   800   10       NA
# 9   900   10       NA
# 10 1000   10       NA
# 11  100   20       NA
# 12  200   20       NA
# 13  300   20       NA
# 14  400   20       NA
# 15  500   20 2.023187
# 16  600   20 2.100367
# 17  700   20 2.167915
# 18  800   20 2.228178
# 19  900   20 2.282705
# 20 1000   20 2.332653

关于r - 使用 sapply() 在两个参数上循环 uniroot(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50978973/

相关文章:

r - 延时绘图

html - 如何编写一个 R 函数来创建一系列散布有 markdown 的绘图

javascript - 如何像显示的示例一样迭代每个数字? (Java 脚本)

python - Python的复杂度是subset()

python - 在Python 3.3中通过循环将键和值迭代到字典中

r - R 数据帧的匹配对

RPostgreSQL 连接在使用 doParallel clusterEvalQ 启动后立即过期

r - 在自定义 R 包中使用 "Matrix"包方法

c++ - 仅在行不为空时递增

java - 需要验证循环,二进制到十进制未输出正确的答案