Is it possible to convert this for loop to an apply family function?

Asked

Viewed 61 times

2

df_loop <- data.frame(data1, data2, data3, 0)

for (i in 4:nrow(df_loop[1]))
{
    tmp_1 = df_loop[i,1]
    tmp_2 = df_loop[i,2]
    tmp_2_lag3 = df_loop[i-3,2]
    tmp_3 = df_loop[i,3]

    if (!is.na(tmp_2_lag3))
    {
        if((tmp_1 > tmp_2) & (tmp_2 > tmp_2_lag3) & (tmp_3 > 1.5))
        {
            df_loop[i,4] = 2
        }
        else
        {
            if((tmp_1 < tmp_2) & (tmp_2 < tmp_2_lag3) & (tmp_3 < -1.5))
            {
                df_loop[i,4] = 4
            }
            else
            {
                if (df_loop[i-1,4] == 2)
                {
                    df_loop[i,4] = 3
                }
                else
                {
                    if (df_loop[i-1,4] == 4)
                    {
                        df_loop[i,4] = 1
                    }
                    else
                    {
                        df_loop[i,4] = df_loop[i-1,4]
                    }
                }
            }
        }
    }
}

1 answer

0

Is this what you wanted? Let me know if it works for you!

df_loop[,5:6] <- NA
df_loop[4:nrow(df_loop),5] <- df_loop[1:(nrow(df_loop)-3),2]
df_loop[2:nrow(df_loop),6] <- df_loop[1:(nrow(df_loop)-1),4]



apply(df_loop[4:nrow(df_loop),], 1, function(x){

  tmp_1 <- x[1]
  tmp_2 <- x[2]
  tmp_2_lag3 <- x[4]
  tmp_3 <- x[3]

  if(!is.na(tmp_2_lag3)){
    if( (tmp_1 > tmp_2) & (tmp_2  > tmp_2_lag3) & (tmp_3 > 1.5) ){
      x[4] <- 2
    } else if( (tmp_1 < tmp_2) & (tmp_2 < tmp_2_lag3) & (tmp_3 < -1.5)  ){
      x[4] <- 4
    } else if(x[6] == 2){
      x[4] <- 3
    } else if(x[6] == 4){
      x[4] <- 1
    } else x[4] <- x[6]
  }

})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.