Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206278

Add a new level of a variable and asign it the mean value of other variables for each id

$
0
0

I want to add a level of a variable in a data frame and asign it the average value of other levels in the same variable. I dont know how to do this. So, I want to add the level "base" in the variable trt. There I want to get the average value of trt "OA" and "OB" for the variables "pointA", "pointB" and "pointC"

id <- rep(1:3,each=5)
trt <- rep(c("A","OA", "B", "OB","base"),3)
pointA <- sample(1:10,15, replace=TRUE)
pointB<- sample(1:10,15, replace=TRUE)
pointC<- sample(1:10,15, replace=TRUE)
df <- data.frame(id,trt,pointA, pointB,pointC)
df
##>   id  trt pointA pointB pointC
##>1   1    A      3      3      5
##>2   1   OA     10      6      4
##>3   1    B      9      9      7
##>4   1   OB     10      5      6
##>5   1 base      9      7      3
##>6   2    A      2      9      6
##>7   2   OA      6      3      4
##>8   2    B      6      4     10
##>9   2   OB      8      2      4
##>10  2 base      9      8      4
##>11  3    A      7      1      8
##>12  3   OA      3     10      2
##>13  3    B      2      4      6
##>14  3   OB      2      2      9
##>15  3 base      3      6      8

df[5,3] <- (df[df$id==1 & df$trt=="OA",3] + df[df$id==1 & df$trt=="OB",3])/2
df[5,4] <- (df[df$id==1 & df$trt=="OA",4] + df[df$id==1 & df$trt=="OB",4])/2
df[5,5] <- (df[df$id==1 & df$trt=="OA",5] + df[df$id==1 & df$trt=="OB",5])/2
df[10,3] <- (df[df$id==2 & df$trt=="OA",3] + df[df$id==2 & df$trt=="OB",3])/2
df[10,4] <- (df[df$id==2 & df$trt=="OA",4] + df[df$id==2 & df$trt=="OB",4])/2
df[10,5] <- (df[df$id==2 & df$trt=="OA",5] + df[df$id==2 & df$trt=="OB",5])/2
df[15,3] <- (df[df$id==3 & df$trt=="OA",3] + df[df$id==3 & df$trt=="OB",3])/2
df[15,4] <- (df[df$id==3 & df$trt=="OA",4] + df[df$id==3 & df$trt=="OB",4])/2
df[15,5] <- (df[df$id==3 & df$trt=="OA",5] + df[df$id==3 & df$trt=="OB",5])/2

I want it to look like:

df
##>   id  trt pointA pointB pointC
##>1   1    A    3.0    3.0    5.0
##>2   1   OA   10.0    6.0    4.0
##>3   1    B    9.0    9.0    7.0
##>4   1   OB   10.0    5.0    6.0
##>5   1 base   10.0    5.5    5.0
##>6   2    A    2.0    9.0    6.0
##>7   2   OA    6.0    3.0    4.0
##>8   2    B    6.0    4.0   10.0
##>9   2   OB    8.0    2.0    4.0
##>10  2 base    7.0    2.5    4.0
##>11  3    A    7.0    1.0    8.0
##>12  3   OA    3.0   10.0    2.0
##>13  3    B    2.0    4.0    6.0
##>14  3   OB    2.0    2.0    9.0
##>15  3 base    2.5    6.0    5.5

Viewing all articles
Browse latest Browse all 206278

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>