0

Maybe a weird question motivated by what I read here

How to increase smoothness of spheres3d in rgl

In the example below, does anybody know how to use a pure dplyr approach instead of sapply? The reason is simply that I tend to use dplyr as much as possible in my workflow. Any suggestion is appreciated.

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

Created on 2020-12-14 by the reprex package (v0.3.0)

larry77
  • 1,309
  • 14
  • 29
  • This isn't related to your question, but: I think `rgl.light` is safe and `rgl.clear` is not, but regardless, it's a good idea to avoid any `rgl.*` functions if you're using `*3d` functions. You should use all one type or all the other, i.e. `light3d` and `clear3d` instead. – user2554330 Dec 15 '20 at 17:36

1 Answers1

1

Here are couple of dplyr/tidyverse approaches :

Use pmap_dbl :

library(dplyr)
library(purrr)

spheres %>%
  mutate(spheres = pmap_dbl(., ~sphere1.f(..1, ..2, ..3)))

Or with rowwise :

spheres %>%
  rowwise() %>%
  mutate(spheres = sphere1.f(x, y, z))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thanks! I missed the idea of using mutate (I thought it was not needed since I do not want to create any extra column, but I suppose this invokes the rgl as a side effect). – larry77 Dec 14 '20 at 16:53