Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining Multiple Identically-Named Columns in R

Tags:

r

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.

like image 498
bac Avatar asked Jan 22 '12 12:01

bac


People also ask

How do I combine multiple columns into one in R?

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 combine column names in R?

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>.

How do I combine columns from a different Dataframe in R?

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.

How do I merge columns in the same name?

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.


1 Answers

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)))
like image 108
digEmAll Avatar answered Sep 29 '22 13:09

digEmAll