【发布时间】:2020-05-22 11:13:23
【问题描述】:
我正在尝试编写一个简单的函数来调整某些几何形状的暴露表面积,具体取决于它们如何相互连接。它看起来像这样:
funct <- function(A, shape, x) {
radius <- x / 2
A <- dplyr::case_when(
shape == "sphere" ~ A - (pi * radius^2),
shape == "cylinder" ~ A - 2*(pi * radius^2),
shape == "ellipsoid" ~ A - (0.2 * A[which(shape == "sphere")] + (2 * pi * radius[which(shape == "cylinder")]))
)
return(A)
}
这很简单,但在实际数据集中经常缺少因子水平,这意味着简单的调整不起作用:
testdata <-
data.frame(ind = paste(letters[1:10]), A = rnorm(10), shape = rep(c("sphere", "ellipsoid"), each = 5), x = rnorm(10))
testdata$Aadj <- funct(A = testdata$A, shape = testdata$shape, x = testdata$x)
#Error: `shape == "ellipsoid"... must be length 10 or one, not 0
我可以通过完成数据集手动解决这个问题:
shapes <- as.vector(c("sphere", "cylinder", "ellipsoid"))
testdata <- tidyr::complete(testdata, ind, shape = shapes, fill=list(A = 0))
testdata$Aadj <- funct(A = testdata$A, shape = testdata$shape, x = testdata$x)
为了使这更简洁,我会对如何处理实际函数中缺失的因子水平的一些输入感兴趣。我认为这可以通过首先将它们添加到数据中来解决(将“A”设置为 0 以允许计算),然后在返回数据之前再次删除它们?
我还对如何在函数中跨主题(testdata df 中的“ind”)循环的建议感兴趣(而不是例如在应用函数时在 dplyr 管道中设置它)。
非常感谢。
【问题讨论】:
-
尝试使用
shape %in% "ellipsoid"而不是==。不确定这是否能解决您的问题,但我发现%in%是一个更合作的运营商。 -
你的预期输出是什么?