0

How can I sum the columns (C1.dn + C2.dn + V1.dn + V2.dn) by each row and display it as a new column in the same dataframe?

For example, sum of row 1 (9.659531 + 5.159067 + 9.220461 + 13.48245) should be displayed as a new column (37.52).

A snippet of my data is provided below.

 C1.dn     C2.dn    V1.dn    V2.dn
1   9.659531  5.159067 9.220461 13.48245
2  13.482264 15.033321 5.249731 15.39126
3  14.986702  8.004261 8.190506 12.43744
4  16.130656 16.455435 7.469901 11.58376
5  11.597134  8.422198 5.798567 12.34388
6  14.337659 15.216855 5.883851 10.27983
7  11.403534  7.947642 7.051602 16.54026
8  20.604107 14.437914 5.023191 12.63318
9  11.324600  7.044436 6.866096 13.99970

Thanks.

Pranav_b
  • 17
  • 4

1 Answers1

0
dat <- read.table(text = " C1.dn     C2.dn    V1.dn    V2.dn
1   9.659531  5.159067 9.220461 13.48245
2  13.482264 15.033321 5.249731 15.39126
3  14.986702  8.004261 8.190506 12.43744
4  16.130656 16.455435 7.469901 11.58376
5  11.597134  8.422198 5.798567 12.34388
6  14.337659 15.216855 5.883851 10.27983
7  11.403534  7.947642 7.051602 16.54026
8  20.604107 14.437914 5.023191 12.63318
9  11.324600  7.044436 6.866096 13.99970", header = T)


dat
dat$newcol <- rowSums(dat)

> dat
      C1.dn     C2.dn    V1.dn    V2.dn   newcol
1  9.659531  5.159067 9.220461 13.48245 37.52151
2 13.482264 15.033321 5.249731 15.39126 49.15658
3 14.986702  8.004261 8.190506 12.43744 43.61891
4 16.130656 16.455435 7.469901 11.58376 51.63975
5 11.597134  8.422198 5.798567 12.34388 38.16178
6 14.337659 15.216855 5.883851 10.27983 45.71820
7 11.403534  7.947642 7.051602 16.54026 42.94304
8 20.604107 14.437914 5.023191 12.63318 52.69839
9 11.324600  7.044436 6.866096 13.99970 39.23483

As stated in your comment, if data contains columns that are non-numeric, you can do the following

iris$newcol <- apply(iris, 1, FUN = function(x)sum(as.numeric(x), na.rm = T))

> head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species newcol
1          5.1         3.5          1.4         0.2  setosa   10.2
2          4.9         3.0          1.4         0.2  setosa    9.5
3          4.7         3.2          1.3         0.2  setosa    9.4
4          4.6         3.1          1.5         0.2  setosa    9.4
5          5.0         3.6          1.4         0.2  setosa   10.2
6          5.4         3.9          1.7         0.4  setosa   11.4
AnilGoyal
  • 14,820
  • 3
  • 16
  • 30
  • Thanks for your answer but my dataframe has more than these four columns (including factor, character etc). When done your way, it says "x should be numeric". – Pranav_b Mar 23 '21 at 09:45
  • @Pranav_b You can use the following code for as many columns as possible: df %>% rowwise() %>% mutate(sum_row = sum(c_across(C1.dn:V2.dn))) – Anoushiravan R Mar 23 '21 at 09:46
  • @Pranav_b, so in that case, would you like to sum only numeric columns? – AnilGoyal Mar 23 '21 at 10:07