R/calculate_get_lpresults.R

Defines functions get_lpresults2

#' extract liquid period results
#'
#' @param df a data frame containing results with lp info
#' @param cursor name of the cursor to use 
#' @param last_n how many datapoints to use
#' 
#' The resulting data frame can be used to annotate an I/plot. 
#' For generating drc's, further processing like normalisation etc is required
#' 
#' PLXLS is not given, use (if s is a Series) 
#' s$add_lpinfo(c(1,3,10, 100, 300, 1000), c(5,15,15,15,15,13), "x")
#'
#' @return data frame
#' @import plyr 
#' 
#' 
#' 
#' @export
get_lpresults2<-function(df, cursor, last_n=3, normalize=F){
  
  if(class(df)=="list"){
    
    return(
      df %>% purrr::map_df(  
        ~get_lpresults2(.,cursor=cursor, last_n=last_n, normalize=normalize)
      )
    )
  }
    
    
  # automatically convert series objects into results, if needed
  if(inherits(df,"HEKAseriesProto"))
    df<-df$results()
  
  if(missing(cursor)) stop ("please supply a cursor name")
  if(is.null(df[[cursor]])) stop("a cursor with this name does not exist")
  if(is.null(df$Concentration)) stop("no columns 'Concentration' in results'")
  if(is.null(df$CompoundName)) df$CompoundName="compound" 
  # function to get the last n element(s) of a vector
  getlast<-function(x,n){x[(length(x)-n+1):length(x)]}
  
  # function to get the mean of last datapoints of a lp
   mean_of_last<-function(df, cursor, n) data.frame( 
     res=mean(getlast(df[,cursor],n)), 
     relTime.start=getlast(df$relTime,n)[1],
     relTime.end=getlast(getlast(df$relTime,n),1)
   )
  
  lpresults<-ddply(df,.(exp_, tracename, Concentration, CompoundName), mean_of_last, cursor, last_n )
  lpresults<-lpresults[,c(5,3,4,1,2, 6,7)] # colums order suitable for drc_
  if(normalize)
    lpresults$res<-lpresults$res/lpresults$res[1]
  lpresults
}
tdanker/ephys2 documentation built on Aug. 11, 2019, 12:12 p.m.