lundi 4 février 2019

dataset value substition not yielding expected result

I have the following two dataframes in R

    df=data.frame("Z_Frequency"=c(5,10,15,20,25), "Z_Slope2"=c(0,.7, 
   -0.5,0,.7))


    df24<-data.frame("Z_Frequency"=seq(from=min(df$Z_Frequency), to = 
    max(df$Z_Frequency), by = 1))

I am populating the values of df24$Z_SSLOPE column by comparing the value of df24$Z_Frequency and df$Z_Frequency. if the value of df24$Z_Frequency is identical to the of df$Z_Frequency, the df24$Z_SSLOPE column value will be copied from df$Z_Slope2. I have written the following code- loop for the same.

  df24$Z_SSLOPE<-0

for( i in 1: nrow(df)){ for (j in 1:nrow(df24)) { 
if(df24$Z_Frequency[j]==df$Z_Frequency[i]){ df24$Z_SSLOPE[j]<- 
df$Z_Slope2[i]} else if(df24$Z_Frequency[j]>df$Z_Frequency[i]& 
df24$Z_Frequency[j]<df$Z_Frequency[i+1]){
df24$Z_SSLOPE[j]=df$Z_Slope2[df24$Z_Frequency[j]>df$Z_Frequency[i] & 
df24$Z_Frequency[j]<df$Z_Frequency[i+1]]}}}

The expected output is as follows

     Z_Frequency Z_SSLOPE
1            5      0.0
2            6      0.7
3            7      0.7
4            8      0.7
5            9      0.7
6           10      0.7
7           11     -0.5
8           12     -0.5
9           13     -0.5
10          14     -0.5
11          15     -0.5
12          16      0.0
13          17      0.0
14          18      0.0
15          19      0.0
16          20      0.0
17          21      0.7
18          22      0.7
19          23      0.7
20          24      0.7
21          25      0.7

In case df24$Z_Frequency values dont find a match in df$Z_Frequency, the values are filled by the next available match of df24$Z_Frequency. I am getting the following output.

     Z_Frequency     Z_SSLOPE
 1            5      0.0
 2            6      0.0
 3            7      0.0
 4            8      0.0
 5            9      0.0
 6           10      0.7
 7           11      0.0
 8           12      0.0
 9           13      0.0
 10          14      0.0
 11          15     -0.5
 12          16      0.0
 13          17      0.0
 14          18      0.0
 15          19      0.0
 16          20      0.0
 17          21      0.0
 18          22      0.0
 19          23      0.0
 20          24      0.0
 21          25      0.7

The first part of the if statement works. However, I am unable to spot the error in the else part of the if statement. I request someone's help.

Aucun commentaire:

Enregistrer un commentaire