Home > Software engineering >  I have two columns mentioning observations before and after treatment. How can I calculate percentag
I have two columns mentioning observations before and after treatment. How can I calculate percentag

Time:09-07

dat$HOMAIR_base = c(1.8, 8.55, 2.34, 4.08, 3.58, 
2.12, 4.56, 4.6, 1.27, 4.18, 2.3, 3.96, 10.05, 3.94, 2.39, 4.5, 
3.82, 10, 3.06, 1.73, 2.96, 5.6, 1.52, 7.71, 2.94, 4.39, 2.64, 
1.5, 2.92, 2.41), 

dat$HOMAIR_4 = c(2.39, 0.42, 1.32, 1.93, 
2.46, 3.08, 3.52, 2.11, 6.82, 2.23, 1.69, 3.91, 3.64, 4.08, 1.77, 
3.7, 12, 4.45, 3.42, 1.96, 3.63, 5.21, 1.52, 7.71, 2.46, 4.42, 
8.39, 0.88, 3.97, 3.03)

CodePudding user response:

dat = data.frame(HOMAIR_base = c(1.8, 8.55, 2.34, 4.08, 3.58, 2.12, 4.56, 4.6, 1.27, 4.18, 2.3, 3.96, 10.05, 3.94, 2.39, 4.5, 3.82, 10, 3.06, 1.73, 2.96, 5.6, 1.52, 7.71, 2.94, 4.39, 2.64, 1.5, 2.92, 2.41),
                 HOMAIR_4 = c(2.39, 0.42, 1.32, 1.93, 2.46, 3.08, 3.52, 2.11, 6.82, 2.23, 1.69, 3.91, 3.64, 4.08, 1.77, 3.7, 12, 4.45, 3.42, 1.96, 3.63, 5.21, 1.52, 7.71, 2.46, 4.42, 8.39, 0.88, 3.97, 3.03))
dat$PercChange = 100 * (dat$HOMAIR_4 - dat$HOMAIR_base) / dat$HOMAIR_base
head(dat)   


  HOMAIR_base HOMAIR_4 PercChange
1        1.80     2.39   32.77778
2        8.55     0.42  -95.08772
3        2.34     1.32  -43.58974
4        4.08     1.93  -52.69608
5        3.58     2.46  -31.28492
6        2.12     3.08   45.28302

CodePudding user response:

Does this work:

library(dplyr)
dat %>% mutate(pct_change = paste(round(100 * ((HOMAIR_4 - HOMAIR_base)/HOMAIR_base), 2), '%', sep = ''))
   HOMAIR_base HOMAIR_4 pct_change
1         1.80     2.39     32.78%
2         8.55     0.42    -95.09%
3         2.34     1.32    -43.59%
4         4.08     1.93     -52.7%
5         3.58     2.46    -31.28%
6         2.12     3.08     45.28%
7         4.56     3.52    -22.81%
8         4.60     2.11    -54.13%
9         1.27     6.82    437.01%
10        4.18     2.23    -46.65%
11        2.30     1.69    -26.52%
12        3.96     3.91     -1.26%
13       10.05     3.64    -63.78%
14        3.94     4.08      3.55%
15        2.39     1.77    -25.94%
16        4.50     3.70    -17.78%
17        3.82    12.00    214.14%
18       10.00     4.45     -55.5%
19        3.06     3.42     11.76%
20        1.73     1.96     13.29%
21        2.96     3.63     22.64%
22        5.60     5.21     -6.96%
23        1.52     1.52         0%
24        7.71     7.71         0%
25        2.94     2.46    -16.33%
26        4.39     4.42      0.68%
27        2.64     8.39     217.8%
28        1.50     0.88    -41.33%
29        2.92     3.97     35.96%
30        2.41     3.03     25.73%
  •  Tags:  
  • r
  • Related