I'd like to combine multiple columns of a data frame in R. Given data that look something like this:
names: 123 256 192 123 256
1 2 8 2 3
4 3 2 9 9
8 7 1 3 8
How would I sum the elements of the identically-named columns to produce a table like so:
names: 123 256 192
3 5 8
13 12 2
11 15 1
Thank you very much.
Convert multiple columns into a single column, To combine numerous data frame columns into one column, use the union() function from the tidyr package.
How do I concatenate two columns in R? To concatenate two columns you can use the <code>paste()</code> function. For example, if you want to combine the two columns A and B in the dataframe df you can use the following code: <code>df['AB'] <- paste(df$A, df$B)</code>.
Method 1 : Using plyr package rbind. fill() method in R is an enhancement of the rbind() method in base R, is used to combine data frames with different columns. The column names are number may be different in the input data frames. Missing columns of the corresponding data frames are filled with NA.
Let's say you want to create a single Full Name column by combining two other columns, First Name and Last Name. To combine first and last names, use the CONCATENATE function or the ampersand (&) operator.
As suggested by @VincentZoonekynd it is not a good idea to have multiple columns with the same name.
Anyway, you could do in this way:
df <- data.frame(A=c(1,4,8),B=c(2,3,7),C=c(8,2,1),D=c(2,9,3),E=c(3,9,8))
names(df) <- c('123','256', '192', '123', '256')
df <- t(df) # transpose the data.frame
aggr <- by(df, INDICES=row.names(df), FUN=colSums) # collapse the rows with the same name
aggr <- as.data.frame(do.call(cbind,aggr)) # convert by() result to a data.frame
or, in one line:
aggr <- as.data.frame(do.call(cbind, by(t(df),INDICES=names(df),FUN=colSums)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With