How to add values in columns having same name and merge them in R?

R ProgrammingServer Side ProgrammingProgramming

To add values in columns having same name and merge them in R, we can follow the below steps −

  • First of all, create a data frame.
  • Add column values that have same name and merge them by using cbind with do.call.

Create the data frame

Let's create a data frame as shown below −

df<-
data.frame(x=rpois(25,1),y=rpois(25,2),x=rpois(25,5),z=rpois(25,2),y=rpois(25,1),z=rpoi
s(25,5),check.names=FALSE)
df

On executing, the above script generates the below output(this output will vary on your system due to randomization) −

  x y x z y z
1 1 1 7 1 1 1
2 3 2 4 0 3 4
3 1 3 4 2 0 3
4 1 1 9 2 3 3
5 1 2 3 0 3 8
6 1 3 2 1 0 4
7 1 2 5 2 2 4
8 0 1 6 3 2 7
9 1 4 4 2 1 1
10 1 2 3 3 0 3
11 2 2 10 1 0 14
12 2 2 2 2 0 1
13 0 3 5 3 0 6
14 2 1 3 2 0 5
15 0 2 5 6 1 4
16 1 2 3 0 0 5
17 0 2 7 2 2 11
18 3 2 4 1 2 5
19 0 7 5 1 0 10
20 0 3 3 1 0 6
21 1 1 5 7 5 6
22 1 0 5 3 2 5
23 3 3 3 3 0 2
24 2 0 6 4 1 7
25 0 7 1 2 1 4

Add column values having same name and merge them

Use do.call function with cbind function to add column values with colSums function as shown below −

df<-
data.frame(x=rpois(25,1),y=rpois(25,2),x=rpois(25,5),z=rpois(25,2),y=rpois(25,1),z=rpoi
s(25,5),check.names=FALSE)
Merged_df<-as.data.frame(do.call(cbind,
by(t(df),INDICES=names(df),FUN=colSums)))
Merged_df

Output

   x y z
V1 8 2 2
V2 7 5 4
V3 5 3 5
V4 10 4 5
V5 4 5 8
V6 3 3 5
V7 6 4 6
V8 6 3 10
V9 5 5 3
V10 4 2 6
V11 12 2 15
V12 4 2 3
V13 5 3 9
V14 5 1 7
V15 5 3 10
V16 4 2 5
V17 7 4 13
V18 7 4 6
V19 5 7 11
V20 3 3 7
V21 6 6 13
V22 6 2 8
V23 6 3 5
V24 8 1 11
V25 1 8 6
raja
Published on 07-Aug-2021 07:53:47
Advertisements