Created
May 21, 2014 18:23
-
-
Save rustyb/ef2e54bf2f210c6e531d to your computer and use it in GitHub Desktop.
This file contains 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
# Create the S4 Class Trajectory | |
setClass("Trajectory", representation(x = "numeric", y = "numeric", time = "numeric")) | |
#make a new object with class Trajectory | |
colin <- new("Trajectory", x = 21.5, y = 21.5, time = 1200) | |
# create the S4 Class TrajectoryExtra which includes the Trajectory class | |
setClass("TrajectoryExtra", representation(speed = "numeric", direction = "numeric"), contains = "Trajectory") | |
colin1 <- new("Trajectory", x = c(0:10), y = c(20:30), time = c(1200:1210)) | |
# define a coercion method (setAs) that coerces from Trajectory to TrajectoryExtra, and which | |
# computes the speed and direction fields from speed and direction fields from x/y/t | |
setAs ("Trajectory", "TrajectoryExtra", | |
function (from , to) { | |
#calculate the speed, first we calculate the magnitude and then we divide this by time to get speed | |
dist = sqrt(from@x^2 + from@y^2) | |
s = dist / from@time | |
#to find the direction we know that the we can use arc tangent to get this. atan(y/x). We need the answer in degrees as R works in radians. | |
direct = atan(from@y/from@x)*(180/pi) | |
new("TrajectoryExtra", x = from@x, y = from@y, time = from@time, speed = s, direction = direct) | |
} | |
) | |
# Test the method | |
as(colin1, "TrajectoryExtra") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment