You can achieve the desired formatting by reshaping your data with a number of methods including using the reshape()
function in Base R or dcast()
in the reshape2
package, but it might be easier to just be able to get to your answer directly using a form of aggregation. Here's one method using ddply()
from the plyr
package:
library(plyr)
df <- read.table(text="id date bp
1 21/1/14 120
1 19/3/14 134
1 3/5/14 127",header=TRUE)
df1 <- ddply(df, .(id), summarize, mean.bp = mean(bp[1:3]))
df1
# id mean.bp
# 1 1 127
Of course, if you really just want to do what you asked about, you can do the following:
library(reshape2)
df$bp.id <- ave(df$id,df$id,FUN=function(x) paste0("BP",seq(along=x)))
df2 <- dcast(df[df$bp.id %in% paste0("BP",1:3)], id~bp.id, value.var="bp")
df2
# id BP1 BP2 BP3
# 1 1 120 134 127