【发布时间】:2020-05-22 16:21:53
【问题描述】:
我正在开发一项功能,根据这些几何形状的拼接方式调整暴露的表面区域。在实际应用中,我经常会处理一些形状的缺失数据,所以我需要在函数中处理。
我想为数据集中的每个主题(“ind”)迭代相同类型的调整。
testdata <-
data.frame(ind = rep(paste(letters[1:10]), each =2), A = rnorm(20, mean = 10, sd = 3), shape = rep(c("sphere", "ellipsoid"), 10),
x = rnorm(10, mean = 5, sd = 1))
funct <- function(A, shape, x, subject) {
#Create NA aware function to deal with missing factor levels
sum_ <- function(...) sum(..., na.rm=T)
radius <- x / 2
A <- dplyr::case_when(
shape %in% "sphere" ~ A - sum_((pi * radius[which(shape %in% 'cylinder')]^2)),
shape %in% "cylinder" ~ A - sum_(2*(pi * radius^2)),
shape %in% "ellipsoid" ~ A - sum_((0.2 * A[which(shape %in% "sphere")]), (2 * pi * radius[which(shape == "cylinder")]))
)
return(A)
}
此函数会产生预期的输出,但仅在我进行非常简单的调整(例如加减)时。当我实际执行上面的代码时,结果很差。
所以我尝试在函数中添加一个循环,但没有运气:
funct <- function(A, shape, x, subject) {
#Create NA aware function to deal with missing factor levels
sum_ <- function(...) sum(..., na.rm=T)
radius <- x / 2
for(levels in levels(subject)) {
A <- dplyr::case_when(
shape %in% "sphere" ~ A - sum_((pi * radius[which(shape %in% 'cylinder')]^2)),
shape %in% "cylinder" ~ A - sum_(2*(pi * radius^2)),
shape %in% "ellipsoid" ~ A - sum_((0.2 * A[which(shape %in% "sphere")]), (2 * pi * radius[which(shape == "cylinder")]))
)
}
return(A)
}
这就是我得到的:
testdata$result <- funct(A = testdata$A, shape = testdata$shape, x = testdata$x, subject = testdata$ind)
这就是我想要的:
testdata <-
testdata %>%
group_by(ind) %>%
mutate(expected = case_when(
shape %in% "sphere" ~ A - sum_((pi * radius[which(shape %in% 'cylinder')]^2)),
shape %in% "cylinder" ~ A - sum_(2*(pi * radius^2)),
shape %in% "ellipsoid" ~ A - sum_((0.2 * A[which(shape %in% "sphere")]), (2 * pi * radius[which(shape == "cylinder")]))
)
)
对于如何正确处理有什么建议吗?
【问题讨论】: