I have the following data frame:
dat <- data.frame(
c = c(1 , 2) , a1 = c(1 , 2) , a2 = c(3 , 4) , b1 = c(5 , 6) , b2 = c(7 , 8)
)
c a1 a2 b1 b2
1 1 1 3 5 7
2 2 2 4 6 8
That I would like to merged columns based on shared prefixes to become this data frame:
dat2 <- data.frame(
c = c(1 , 2 , 1 , 2) , a = c(1 , 2 , 3 , 4) , b = c(5 , 6 , 7 , 8)
)
c a b
1 1 1 5
2 2 2 6
3 1 3 7
4 2 4 8
The only way I can think of is to try do this using melt()
. This was my attempt:
melt(dat , measure.vars = c(grep("^a" , colnames(dat)) , grep("^b" , colnames(dat))))
variable value
1 1 a1 1
2 2 a1 2
3 1 a2 3
4 2 a2 4
5 1 b1 5
6 2 b1 6
7 1 b2 7
8 2 b2 8
>
Needless to say, this is incorrect.