lundi 22 février 2021

Replace outrange values refer to another dataframe for each row in r

I post this question to improve my current method. Thanks for helping me!

I have two dataframes.

Data A is my measurements:

           site 1   site 2  site 3  site 4  site 5  site 6  site 7
1/1/2020    76       44     51        1     18        42     69 
1/2/2020    80       55     52        30    17        38     12 
1/3/2020    36       60     45        44    23        86      4 
1/4/2020    6        73     87        15    96        56     22 
1/5/2020    100      71     58        69    42        11     69 
1/6/2020    6        92     48        73    31        45     89 
1/7/2020    46       52     43        90    2         20      8 
1/8/2020    83       32     23        12    80        64     79 
1/9/2020    63       25     74        79    17        29     88 
1/10/2020   91       53     41        11    29        48     67 
1/11/2020   82       3      32        56    56        61     35 
1/12/2020   55       66     69        88    75        78     88 
1/13/2020   75       52     74        78    30        17     41 
1/14/2020   43       72     24        85    10        75     32 

Data B is my range data. The range(min, max) is NOT calculated from Data A.

           min  max
1/1/2020    6   60
1/2/2020   10   70
1/3/2020    5   90
1/4/2020    4   100
1/5/2020    10  100
1/6/2020    3   88
1/7/2020    8   99
1/8/2020    8   101
1/9/2020    7   83
1/10/2020   4   97
1/11/2020   5   89
1/12/2020   9   96
1/13/2020   11  85
1/14/2020   5  103

I want to truncate the Data A refer to Data B. Replace outrange value to the min and max values in Data B.

This is what I have tried.

for (i in 1: 14){
  
  for (j in 1:7){
  
  if (A[i, j]< B[i,1]) {
    
    A[i,j]<-B[i,1]
    
  }
  
  else if (A[i, j]> B[i,2]) {
    
    A[i,j]<-B[i,2]
    
  }
  
  }
  
}

14 is the row numbers in A. 7 is the column numbers in A. Row numbers of A nad B are the same.

I have a very large amount of data. Could anyone tell me a faster approach?

Thank you for your time!

Aucun commentaire:

Enregistrer un commentaire