Search code examples
rdplyrrgl

Dply and RGL: replace sapply


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)


Solution

  • 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))