I have a dataframe like this
ID <- c(101,101,101,102,102,102,103,103,103)
Pt_A <- c(50,100,150,20,30,40,60,80,90)
df <- data.frame(ID,Pt_A)
+-----+------+
| ID | Pt_A |
+-----+------+
| 101 | 50 |
| 101 | 100 |
| 101 | 150 |
| 102 | 20 |
| 102 | 30 |
| 102 | 40 |
| 103 | 60 |
| 103 | 80 |
| 103 | 90 |
+-----+------+
I want to create 2 new columns with values calculated from Pt_A column.
df$Del_Pt_A <- NthRow(Pt_A) - 1stRow(Pt_A) grouped by ID, where n = 1,2,...n
df$Perc_Pt_A <- NthRow(Del_Pt_A) / 1stRow(Pt_A) grouped by ID, where n = 1,2,...n
Here is my desired output
+-----+------+---------+-----------+
| ID | Pt_A | Del_Pt_A | Perc_Pt_A|
+-----+------+---------+-----------+
| 101 | 50 | 0 | 0 |
| 101 | 100 | 50 | 1.0 |
| 101 | 150 | 100 | 2.0 |
| 102 | 20 | 0 | 0 |
| 102 | 30 | 10 | 0.5 |
| 102 | 40 | 20 | 1.0 |
| 103 | 60 | 0 | 0 |
| 103 | 80 | 20 | 0.3 |
| 103 | 90 | 30 | 0.5 |
+-----+------+---------+-----------+
I currently get the desired result in MS Excel but I want to learn to do it in R to make my work efficient. I came across packages like dplyr, plyr, data.table etc but I couldn't solve it using those. Could some one please help me figure out how to work around this.
Here's a data.table way:
which gives