Dply 和 RGL:替换 sapply
Dply and RGL: replace 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 package (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))
也许是我在这里读到的内容引发的一个奇怪的问题
在下面的示例中,有人知道如何使用纯 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 package (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))