rdataframecoordinates

Debugging Error: Non-Numeric Argument in R Function for Calculating Animal Movement


I have an animal movement dataset ("data") that looks like this:

Data
ID Time                x                y            u            v
A  2008-02-01 12:00:00 9155834.12606686 -1085858.899 -0.248678702 0.244811689
A  2008-02-02 12:00:00 9156464.06545883 -1085782.058 -0.251412658 0.247100772   
A  2008-02-03 12:00:00 9156466.83719953 -1085785.249 -0.251420536 0.247112624
A  2008-02-04 12:00:00 9160775.91409932 -1083780.819 -0.273312639 0.262021876

I am using the following function code in R studio to process this data:

bear_move  <- function(data)
{
  #make sure data is ordered properly
  data <- data[order(data$ID, data$time),]
  
  #identify last locations for each bear
  last_locs <- c(which(data$ID[-1] != data$ID[-nrow(data)]), nrow(data))
  
  ## start point of step 
  start <- as.matrix(data[,c("x", "y")])
  
  #end point of step
  end <- rbind(as.matrix(start[-1,]), NA)
  
  #difference in time between steps (first to NEXT location)
  dt <- c(as.numeric(difftime(data$time[2:nrow(data)],data$time[1:nrow(data)-1], units="hours")), NA) 

  #u and v components of ice drift 
  uv <- as.matrix(data[,c("u", "v")])
  
  ## calculate change in x,y abd u,v
  delta_xy <- end - start
  delta_uv <- uv*dt
  
  #initialize matrix for bear movement
  delta_bear <- matrix(NA, nrow=nrow(delta_xy), ncol=2)
  # idenitify which u/v estimates are NA
  notNA <- which(!is.na(delta_uv))
  #bear move = x-u and y-v 
  delta_bear[notNA] <- delta_xy[notNA] - delta_uv[notNA]
  # bear move == delta_xy for NA estimates
  delta_bear[-notNA] <- delta_xy[-notNA] 
  
  #calculate bear movement with Pythagorean Theorem
  bear_move <- sqrt(rowSums(delta_bear^2))
  
  #put NA for last step for each bear
  bear_move[last_locs] <- NA
  
  return(bear_move)
}

This function should create a new column in my dataset called bear_move. However, when I try to activate the function using the line bear_move(data) , I get the following error message:

Error in end - start : non-numeric argument to binary operator

I'm not sure what this error is due to. Any ideas on how to fix this?


Solution

  • From your dataset you need to remove the non numeric input, like date and ID you need to transform the ID column otherwise your dataset is fine and your function will work as there is no missing/NA value in your dataset, all data inputs in your dataset are also current

    check the datatypes by following commands:

    class(start)
    class(end)
    

    these functions will inspect the data types of your dataset variables

    Here you can easily ensure that they are not numeric or integer. which is true as I have explained above, so convert them and again run the code it will work

    to convert the variables you can use the following methods

    start<-as.numeric(start)
    end<- as.numeric(end)
    

    I hope it will help you cheers :)