vendredi 26 mars 2021

Nesting if else statements

I have a large dataset I need to recode. Each row of the dataset is a possible detection from separate experiments (id) in chronological order (time). Each possible detection is then manually verified. When the first true detection is made it is marked (comments) 'first' when the last true detection is made it is marked 'last'. The dataset is somewhat more complex than than that, but I am going to focus on the specific code case that I can't get to work.

I am approaching recoding with if statements. First I want to select all cases where first and last are present (there are other cases where first and last are absent from an experiment, but those are working and not shown here), then it needs to fill in everything between first and last with 'no_comment', then it needs to fill in everything before or after first and last with "MVND". The individual lines of code are working, but for some reason they aren't working together when I combine them in an if statement. I assume I have the wrong if else structure for what I want to do.

#approximate data structure for this case:
y <-data.frame(id=c(rep("a",10),rep("b",10),rep("c",10)),time=rep(1:10, 3), Comments=rep(NA,30))
 y$Comments[c(2,11,23)]<-"first"
 y$Comments[c(9,19,30)]<-"last"
 #x=y[y$id=="a",] #testing specific lines
 
#recursive process to step through the data
 ddply(y,.(id), .fUN=function(x){
 if(all(unique(na.omit(x$Comments))%in%c("first","last"))){
  f<-which(x$Comments == "first")
  l<-which(x$Comments == "last")  
  #Add no comment to all records between first and last
   x$Comments[(f+1):(l - 1)]<- "no_comment"
      #if 'first' isn't the first record add MVND to all things before 'first'    
       if(f>1){x$Comments[1:(f-1)]<-"MVND"} 
      #if 'last' isn't the last record add MVND to all records after 'last'.
       if(l<nrow[x]){x$Comments[(l+1):nrow(x)]<-"MVND"} 
 }else{#do other stuff to experiments that don't have first/last
     }
 }
 )

if data tables are a better way to do this I am game to find out how to do this in a dt.

Aucun commentaire:

Enregistrer un commentaire