Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
950 views
in Technique[技术] by (71.8m points)

loops - Syntax in R for prediction

How do I perform this loop in RStudio using R library? Actually my dataset has over 100,000 rows and need some efficient syntax that can produce something similar to this for loop

Use previous row's value to predict for next all rows(in col d) after rows when data not available

# df is a dataframe with columns b,c,d,p.
        
    
    d = c(1, 2, 4, NA, NA)
    b = c(1,1,1,2,2) 
    c=c(1,1,1,1,1)
    
    df= data.frame(cbind(b,c,d))
    df$p <- c(0.1,0.2,0.1,0.1,0.3)
    
    for(i in 1:(nrow(df)-1)) {
      if (df$b[i + 1] > df$c[i + 1]) {
        df$d[i + 1] = df$d[i] * (1 - df$p[i + 1])
      } else{
        df$d[i + 1] = df$d[i+1]
      }
    }
question from:https://stackoverflow.com/questions/65840586/syntax-in-r-for-prediction

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This vectorized code gives the same output as the question's for loop. And is much faster.

inx <- seq_along(df$a)[-1]
b_greater <- df$b[inx] > df$c[inx]
df$a[inx] <- df$d[inx - 1]
df$a[inx][b_greater] <- df$d[inx - 1][b_greater] * (1 - df$p[inx][b_greater])

df
#  b c  d   a   p
#1 1 1  1  NA 0.1
#2 1 1  2 1.0 0.2
#3 1 1  4 2.0 0.1
#4 2 1 NA 3.6 0.1
#5 2 1 NA  NA 0.3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...