dataframe - Decremental multiplication in R -


below sample dataframe df, many variables c 1 among them, length of column in variable.

 id c  1  0  2  1.47349678  3  0  4  0  5  0  6  0  7  0  8  0  9  0 10  0 11  0 12  0 13  0 14  0 16  1.987 17  0 18  0 19  0 20  0 21  0 22  0 23  0 24  0 25  0 26  0 27  0 

i need create variable c_c consists of product of cand decremental factor 0.1.
multiplication has done count of 10 values of c_c point there value of cother 0. result has stored next data point. i.e if c !=0 found @ id ==2 product must stored id==3
if there less 10 continuous zeroes after non 0 number count reset new value of c, , if there no further data found multiplication stop.

expected result

   id   c              c_c    1    0              0    2    1.47349678     0    3    0              1.47349678    4    0              1.326147102    5    0              1.178797424    6    0              1.031447746    7    0              0.884098068    8    0              0.73674839    9    0              0.589398712   10    0              0.442049034   11    0              0.294699356   12    0              0.147349678   13    0              0   14    0              0   16    1.987          0   17    0              1.987   18    0              1.7883   19    0              1.5896   20    0              1.3909   21    0              1.1922   22    0              0.9935   23    0              0.7948   24    0              0.5961   25    0              0.3974   26    0              0.1987   27    0               0 

observation required result
1. value in c not 0is enocunter @ id = 2, product being stored id == 3 i.e c_c3.
2. c_c3 == c2 * 1, c_c4 == c2*0.9, c_c5 == c2 * 0.8......c_c12 == c*0.1, c_c13 == c2 *0.
3. c_c17 == c16 * 1, c_c18 == c16*0.9, c_c19 == c16 *0.8, .... c_c26 == c16 *0.1, c_c27 == c16*0

thanks!

with dplyr:

library(dplyr)    df$group = cumsum(dt$c>0) df = df %>% group_by(group) %>% mutate(value=sum(c)) %>%   mutate(n=1.1-0.1*(row_number()-1)) %>% mutate(n=ifelse(n<0|value==0|n==1.1,0,n)) %>%   mutate(c_c = n*value) %>% ungroup() %>% select(-n,-group,-value) %>% as.data.frame()     id     c    c_c 1   1 0.000 0.0000 2   2 1.473 0.0000 3   3 0.000 1.4735 4   4 0.000 1.3261 5   5 0.000 1.1788 6   6 0.000 1.0314 7   7 0.000 0.8841 8   8 0.000 0.7367 9   9 0.000 0.5894 10 10 0.000 0.4420 11 11 0.000 0.2947 12 12 0.000 0.1473 13 13 0.000 0.0000 14 14 0.000 0.0000 15 16 1.987 0.0000 16 17 0.000 1.9870 17 18 0.000 1.7883 18 19 0.000 1.5896 19 20 0.000 1.3909 20 21 0.000 1.1922 21 22 0.000 0.9935 22 23 0.000 0.7948 23 24 0.000 0.5961 24 25 0.000 0.3974 25 26 0.000 0.1987 26 27 0.000 0.0000 

Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -