This should do the trick, using your data:
d <- data.frame(id = rep(c("key1", "key2"), each = 3), x = c(10, 12, NA, 2, 3, NA))
library(plyr)
d2 <- ddply(d, .(id), transform, x=ifelse(is.na(x), mean(x, na.rm=T), x) )
Here, we split the dataframe by your key
and transform x
depending on whether or not it is NA
. The result is
id x
1 key1 10.0
2 key1 12.0
3 key1 11.0
4 key2 2.0
5 key2 3.0
6 key2 2.5