r - Take the difference based on ID -


i have df 212 rows in form of:

id visit treatment value1 value2 value3 1    v0             2.6     3.4   .1 1    v1             2.3     4.6   .5 2    v0      b        1.3     5.4   .6 3    v0             1.6     5.4   .7 2    v1      b        1.8     4.5   .3 3    v1             1.3     7.3   1.2 

so o have column id, 1 visit week , treatment , bunch of columns values. want take difference each id, treatment same each id, never change week 0 , 1. id don't comes in order. possible?

it like:

id visit treatment value1 value2 value3  1  v0-v1          0.3   -1.2     -.4 

and on.

here's data.table solution:

dt[by=.(id,treatment),j={     z <- nrow(.sd);     c(         .(visit=paste0(visit[1l],'-',visit[z])),         lapply(mget(grep(value=t,'^value',names(.sd))),function(x) x[1l]-x[z])     ); }]; ##    id treatment visit value1 value2 value3 ## 1:  1         v0-v1    0.3   -1.2   -0.4 ## 2:  2         b v0-v1   -0.5    0.9    0.3 ## 3:  3         v0-v1    0.3   -1.9   -0.5 

data

library(data.table); dt <- data.table(id=c(1l,1l,2l,3l,2l,3l),visit=c('v0','v1','v0','v0','v1','v1'),treatment=c( 'a','a','b','a','b','a'),value1=c(2.6,2.3,1.3,1.6,1.8,1.3),value2=c(3.4,4.6,5.4,5.4,4.5,7.3), value3=c(0.1,0.5,0.6,0.7,0.3,1.2)); 

Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -