Binding columns with similar column names in the same dataframe in R
r
Solution
This will do the trick, I suppose.
Explanation
`df[,names(df) == 'a']` will select all columns with name `a`
`unlist` will convert above columns into 1 single vector
`unname` will remove some stray rownames given to these vectors.
`unique(names(df))` will give you unique column names in `df`
`sapply` will apply the inline function to all values of `unique(names(df))`
> df
a b c a b c a b c
1 0 1 2 5 6 2 0 1 2
2 1 2 3 6 7 3 1 2 3
3 2 3 4 7 8 4 2 3 4
> sapply(unique(names(df)), function(x) unname(unlist(df[,names(df)==x])))
a b c
[1,] 0 1 2
[2,] 1 2 3
[3,] 2 3 4
[4,] 5 6 2
[5,] 6 7 3
[6,] 7 8 4
[7,] 0 1 2
[8,] 1 2 3
[9,] 2 3 4
Problem
I have a data frame that looks somewhat like this: ``` df <- data.frame(0:2, 1:3, 2:4, 5:7, 6:8, 2:4, 0:2, 1:3, 2:4) colnames(df) <- rep(c('a', 'b', 'c'), 3) > df a b c a b c a b c 1 0 1 2 5 6 2 0 1 2 2 1 2 3 6 7 3 1 2 3 3 2 3 4 7 8 4 2 3 4 ``` There are multiple columns that have the same name. I would like to rearrange the data frame so that the columns with the same names combine into their own supercolumn, so that there are only unique column names left, for example: ``` > df a b c 1 0 1 2 2 1 2 3 3 2 3 4 4 5 6 2 5 6 7 3 6 7 8 4 7 0 1 2 8 1 2 3 9 2 3 4 ``` Any thoughts on how to do this? Thanks in advance!