• First of all, create a data frame with some columns having same name.

  • Then, use tapply along with co">

    How to find the row total of columns having same name in R data frame?



    To find the row total of columns having same name in R data frame, we can follow the below steps −

    • First of all, create a data frame with some columns having same name.

    • Then, use tapply along with colnames and sum function to find the row total of columns having same name.

    Example

    Create the data frame

    Let’s create a data frame as shown below −

    df<-
    data.frame(x=rpois(25,1),y=rpois(25,10),x=rpois(25,5),y=rpois(25,5),check.names=FALSE)
    df

    Output

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

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

    Find the row total of columns having same name

    Using tapply along with colnames and sum function to find the row total of columns having same name in data frame df −

    df<-
    data.frame(x=rpois(25,1),y=rpois(25,10),x=rpois(25,5),y=rpois(25,5),check.names=FALSE)
    t(apply(df,1, function(x) tapply(x,colnames(df),sum)))

    Output

            x y
    [1,]   8 22
    [2,]   9 22
    [3,]  11 18
    [4,]   6 17
    [5,]   6  8
    [6,]   4 15
    [7,]   4 12
    [8,]   5 12
    [9,]   6 16
    [10,]  9 14
    [11,]  8 18
    [12,]  7 21
    [13,]  5 20
    [14,]  7 17
    [15,]  4 27
    [16,]  8 15
    [17,]  4 20
    [18,] 12 10
    [19,]  6 15
    [20,] 10 13
    [21,] 11 11
    [22,]  2 15
    [23,]  3 12
    [24,]  4 12
    [25,]  5 12
    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements