I have the following data:
Group Subject Lab LabValue Visit Baseline Count
1 001 Lab1 10 Day 1 Y 1
1 001 Lab1 11 Day 2 2
1 001 Lab1 12 Day 30 3
1 002 Lab1 11 Day 1 Y 1
1 002 Lab1 12 Day 30 2
2 005 Lab1 9 Day 1 Y 1
2 005 Lab1 16 Day 2 2
2 005 Lab1 11 Month 1 3
2 006 Lab1 18 Day 1 Y 1
2 006 Lab1 10 Day 2 2
I would like to create two tables:
The first table which displays change from baseline values for Lab1, which calculates the mean at visit and recalculates the baseline with the new subset of patients with that particular visit:
Visit NumberSubjects VisitMean BaselineMean MeanChangeFromBaseline
Baseline 4 12 12 .
Day 2 3 12.3 13 -0.67
Day 30 2 12 10.5 +1.5
Month 1 1 11 9 +2
The second table allows for the option of 'pushing' the last visit all of the subjects without a visit at Month 1 in to the Month 1 row (i.e. subjects 001, 002, and 005):
Visit NumberSubjects VisitMean BaselineMean MeanChangeFromBaseline
Baseline 4 12 12 .
Month 1 4 11.25 12 -0.75
(For subjects 001 and 002, the values on Day 30 become the values for Month 1; for subject 006, the value for Day 2 becomes the value for Month 1).
This is quite complex but I wanted to see if there was a method for doing this using dplyr.
I believe I can select the last value for each subject with the following code:
do.call("rbind",
by(df, INDICES=df$Subject, FUN=function(DF) DF[which.max(DF$count), ]))
Any insight as to how i can create these two tables would be appreciated.