0

I want to make a function which run through all the ids and ends with a list of the differences in score between trt S and trt A, B and C for each id. I don't know how to make the function run through all ids, does anyone have a good suggestion?

id <- rep(1:4, each=4)
trt <- rep(c("S","A","B","C"),4)
score <- sample(1:10,16, replace=TRUE)

df <- data.frame(id, trt,score)
df
   id trt score
1   1   S     9
2   1   A     2
3   1   B     2
4   1   C     5
5   2   S     2
6   2   A     7
7   2   B     9
8   2   C     9
9   3   S     9
10  3   A     3
11  3   B     8
12  3   C     7
13  4   S    10
14  4   A     2
15  4   B     6
16  4   C     3

S <- df[df$id==1 & df$trt=="S",3]   
A <- df[df$id==1 & df$trt=="A",3] 
B <- df[df$id==1 & df$trt=="B",3] 
C <- df[df$id==1 & df$trt=="C",3] 

diffSA <- S-A
diffSB <- S-B
diffSC <- S-C
diff <- data.frame(diffSA, diffSB, diffSC)

Try to put the code in a function:

test <- function (i) {
  S <- df[df$id==1 & df$trt=="S",3]   
  A <- df[df$id==1 & df$trt=="A",3] 
  B <- df[df$id==1 & df$trt=="B",3] 
  C <- df[df$id==1 & df$trt=="C",3] 

  diffSA <- S-A
  diffSB <- S-B
  diffSC <- S-C
  diff <- data.frame(diffSA, diffSB, diffSC)
  return(diff)
}
user11916948
  • 944
  • 5
  • 12

1 Answers1

3

Maybe you can use the following code

dfs <- split(df,df$trt)
res <- data.frame(lapply(dfs[1:3],function(x) dfs[[4]]$score - x$score))
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81