问题描述
此功能根据给定的直径,流量和长度来计算管道中的压力损失.
This function that calculates the pressure loss in a pipe given its diameter, flowrate, and length.
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()和两个任意值作为流和长度:
I'm looking for the smallest diameter that will keep the pressure loss within 2 psi. The range of diameters is between 2 and 12 inches. Using uniroot() and two arbitrary values for flow and length:
intercept = 2L
uniroot(
function(x) hazwil2(x, 100, 400) - intercept ,
interval = c(2, 12)
)$root
现在我正在尝试在流和长度值的这个数据集上循环uniroot
Now I'm trying to loop uniroot on this dataset of values of flow and length
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
)
推荐答案
考虑对 f 和 l 参数进行 unitroot 调用的泛化,以及将其传递给mapply
( m 适用)以逐元素向下迭代数据帧的等长向量(即列, flow 和 length ) ):
Consider generalizing your unitroot call for f and l params, and pass it in mapply
(multiple apply) to iterate elementwise down the equal length vectors (i.e., columns, flow and length of dataframe):
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
:
For a larger set which can potentially yield root issues, consider wrapping function call in tryCatch
to return 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
这篇关于使用sapply()在两个参数上循环uniroot()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!