Last active
February 1, 2017 06:46
-
-
Save benjamin-chan/70b42112691eca0ec1429b211b7468f2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cart2sph <- function (x, y, z, x0 = 0, y0 = 0, z0 = 0, units = "rad") { | |
# See http://mathworld.wolfram.com/SphericalCoordinates.html and https://en.wikipedia.org/wiki/Spherical_coordinate_system | |
# Use ISO convention | |
# rho = radial distance | |
# theta = polar angle (inclination); default units is radians | |
# phi = azimuthal angle; default units is radians | |
x <- x - x0 | |
y <- y - y0 | |
z <- z - z0 | |
rho <- sqrt(x^2 + y^2 + z^2) | |
theta <- acos(z / rho) | |
phi <- atan(y / x) | |
if (units == "deg") { | |
k <- 180 / pi | |
theta <- theta * k | |
phi <- phi * k | |
} | |
data.frame(rho, theta, phi) | |
} | |
s <- 3 | |
scale <- 10 | |
df <- data.frame(x1 = round(runif(s) * scale, 1), | |
y1 = round(runif(s) * scale, 1), | |
z1 = round(runif(s) * scale, 1), | |
x2 = round(runif(s) * scale, 1), | |
y2 = round(runif(s) * scale, 1), | |
z2 = 0) | |
library(magrittr) | |
library | |
df %>% mutate(radial = cart2sph(x1, y1, z1, x2, y2, z2, units = "deg")[, "rho"], | |
azimuthal = cart2sph(x1, y1, z1, x2, y2, z2, units = "deg")[, "theta"], | |
polar = cart2sph(x1, y1, z1, x2, y2, z2, units = "deg")[, "phi"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment