r - Dply 和 RGL:替换 sapply
问题描述
也许是我在这里读到的内容激发了一个奇怪的问题
在下面的示例中,有人知道如何使用纯 dplyr 方法而不是 sapply 吗?原因很简单,我倾向于在我的工作流程中尽可能多地使用 dplyr。任何建议表示赞赏。
library(tidyverse)
library(rgl)
sphere1.f <- function(x0 = 0, y0 = 0, z0 = 0, r = 1, n = 101, ...){
f <- function(s,t){
cbind( r * cos(t)*cos(s) + x0,
r * sin(s) + y0,
r * sin(t)*cos(s) + z0)
}
persp3d(f, slim = c(-pi/2,pi/2), tlim = c(0, 2*pi), n = n, add = T, ...)
}
spheres = data.frame(x = c(1,2,3), y = c(1,3,1), z=c(0,0,0) )
open3d()
#> Warning in par3d(userMatrix = structure(c(1, 0, 0, 0, 0, 0.342020143325668, :
#> font family "sans" not found, using "bitmap"
#> glX
#> 1
material3d(ambient = "black", specular = "grey60", emission = "black", shininess = 30.0)
rgl.clear(type = "lights")
rgl.light(theta = -30, phi = 60, viewpoint.rel = TRUE, ambient = "#FFFFFF", diffuse = "#FFFFFF", specular = "#FFFFFF", x = NULL, y = NULL, z = NULL)
rgl.light(theta = -0, phi = 0, viewpoint.rel = TRUE, diffuse = "gray20", specular = "gray25", ambient = "gray80", x = NULL, y = NULL, z = NULL)
sapply(1:NROW(spheres), function(i)
sphere1.f( spheres$x[i], spheres$y[i], spheres$z[i], r=0.5, col = "pink") )
#> surface surface surface
#> 14 15 16
由reprex 包(v0.3.0)于 2020-12-14 创建
解决方案
这里有几个dplyr
/tidyverse
方法:
使用pmap_dbl
:
library(dplyr)
library(purrr)
spheres %>%
mutate(spheres = pmap_dbl(., ~sphere1.f(..1, ..2, ..3)))
或与rowwise
:
spheres %>%
rowwise() %>%
mutate(spheres = sphere1.f(x, y, z))
推荐阅读
- bash - 无法停止服务器。PostgreSQL
- python - multiprocessing.dummy.Pool 的 join/terminate 方法缓慢
- javascript - Struts 1 Action Forward 返回 404
- c - 如何使用 pwm atmega avr 增加亮度或调暗 LED
- laravel - 如何使用碳重新格式化 dm Y 日期类型?
- javascript - 连接恢复时如何使用服务工作者(Workbox)处理 AJAX 响应
- html - 从角度 4 中的另一个组件按钮单击触发按钮
- python - 将大列表转换为熊猫数据框时出错
- javascript - 通过 Ajax 将 PHP 值返回给 Javascript
- mysql - MariaDB 10.0:根据列值将 1 行拆分为多行