How to find the row sums by excluding a column in R data frame?

R ProgrammingServer Side ProgrammingProgramming

Suppose we have a numerical column in an R data frame that we do not want to include our analysis due to some characteristics such is similarity or distinction with the rest of the data then we might want to exclude that column from the analysis. One such situation would be finding the row sums by excluding a column. For this purpose, we can use the below steps −

  • First of all, creating a data frame.
  • Finding the row sums with the help of mutate function of dplyr package and setdiff function in base R

Create the data frame

Let's create a data frame as shown below −

 Live Demo

x1<-round(rnorm(20),2)
x2<-round(rnorm(20),2)
x3<-round(rnorm(20),2)
df<-data.frame(x1,x2,x3)
df

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

   x1    x2    x3
1 0.67  0.63 -0.12
2 -0.41 0.36 -1.14
3 0.73  0.85  0.29
4 -3.14 0.16  0.65
5 -0.07 0.76  0.07
6 -0.05 -0.26 -2.03
7 -1.61 0.36  0.88
8 -1.48 -0.90 1.10
9 - 2.27 -2.92 -0.06
10 -0.78 -1.89 -0.10
11 -0.06 -1.30 -1.43
12 -0.15 -0.57 0.40
13 0.31 -0.46 -0.46
14 -0.40 -0.16 -1.06
15 -0.07 -1.62 -0.23
16 0.29  0.00  0.29
17 -0.61 0.53 1.67
18 0.86 -0.54 -1.40
19 0.85 0.17 -0.37
20 0.61 -1.46 0.27

Finding the row sums

Using mutate function of dplyr package to find the row sums by excluding the column x3 with setdiff function −

x1<-round(rnorm(20),2)
x2<-round(rnorm(20),2)
x3<-round(rnorm(20),2)
df<-data.frame(x1,x2,x3)
library(dplyr)
df %>% mutate(RowSum=rowSums(.[setdiff(names(.),"x3")]))

Output

   x1    x2    x3  RowSum
1  0.67  0.63 -0.12 1.30
2  -0.41 0.36 -1.14 -0.05
3  0.73  0.85  0.29  1.58
4 -3.14  0.16  0.65 -2.98
5 -0.07  0.76  0.07  0.69
6 -0.05 -0.26 -2.03 -0.31
7 -1.61  0.36  0.88 -1.25
8 -1.48 -0.90  1.10 -2.38
9 -2.27 -2.92 -0.06 -5.19
10 -0.78 -1.89 -0.10 -2.67
11 -0.06 -1.30 -1.43 -1.36
12 -0.15 -0.57 0.40 -0.72
13  0.31  -0.46 -0.46 -0.15
14 -0.40 -0.16 -1.06 -0.56
15 -0.07 -1.62 -0.23 -1.69
16  0.29  0.00  0.29 0.29
17 -0.61  0.53  1.67  -0.08
18  0.86 -0.54 -1.40 0.32
19  0.85 0.17 -0.37 1.02
20  0.61 -1.46 0.27 -0.85
raja
Published on 05-Aug-2021 12:31:02
Advertisements