With the data.table package (which has an improved implementation of the melt
and dcast
functions of reshape2) you could do this as follows:
newdf <- dcast(setDT(df)[, idx := 1:.N, by = id], id ~ paste0("bp",idx), value.var = "bp")
Or utilizing the new rowid
function:
newdf <- dcast(setDT(df), id ~ rowid(prefix="bp",id), value.var = "bp")
both options give the same result:
> newdf
id bp1 bp2 bp3
1: 1 120 134 129
2: 2 110 124 119
But as @SamDickson said, when you want to calculate the mean of (for example) the first two blood pressure measurements, then you can also add a new variable to your existing dataframe df
with:
# using base R
df$first2mn <- ave(df$bp, df$id, FUN = function(x) mean(x[1:2]))
# using data.table
setDT(df)[, first2mn := mean(bp[1:2]), id]
which both give:
> df
id date bp first2mn
1: 1 21/1/14 120 127
2: 1 19/3/14 134 127
3: 1 3/5/14 129 127
4: 2 21/1/14 110 117
5: 2 19/3/14 124 117
6: 2 3/5/14 119 117
Or just calculate the mean with:
# using base R
aggregate(bp ~ id, df, function(x) mean(x[1:2]))
# using data.table
setDT(df)[, .(bp = mean(bp[1:2])), id]
which both give:
id bp
1 1 127
2 2 117
Used data:
df <- read.table(text="id date bp
1 21/1/14 120
1 19/3/14 134
1 3/5/14 129
2 21/1/14 110
2 19/3/14 124
2 3/5/14 119", header=TRUE)