mardi 18 juillet 2017

apply with if function in R

I created a function to create columns with latent variable regarding the date of each observations. The function is working but very slow to compute and i would like to put the loop with i in an apply() but i can't find a way to make it work. I would be greatfull for any help, thanks in advance

type_latent = function(data,num_col_date,num_col_value,nb_of_date,type_latent2,vect_date){

  require(lubridate)

  # date to start the loop regarding the nb of weeks 
  index_date = data[1,num_col_date] + type_latent2(max(vect_date))
  i_index = which(data[,num_col_date] == index_date)

  #first loop to create n columns
  for ( j in 1:nb_of_date){
    data[,(ncol(data) + (j-(j-1)))] = NA
  }

  # Second loop that will feel the Nas with the value at - week(n)

  for ( k in 1:nb_of_date){
    print(k)

    for ( i in (i_index):(nrow(data))){

      temp = 0
      temp = data[i ,num_col_date] - type_latent2(vect_date[k])

      if (length(data[data$date_time == temp,num_col_value]) != 0 & !is.na(temp)){

        data[i,(ncol(data))-(nb_of_date - k)] = data[data$date_time == temp,num_col_value]
      }

    }


  print(index_date)

  #data = data.frame(data[-c(1:index_date),])
  return(data)

}


data = type_latent(data,5,6,2,weeks,c(1,2))

Aucun commentaire:

Enregistrer un commentaire