-1

I have created a table where I have entered some values in the first three columns. I now want to compute the sum of all the cells in each row separately in a fourth column.
eg:

v1 v2 v3 v4
1  2  3  6 
4  5  6  15  

Here, there are some values in the first three columns and the fourth column has the sum of the first three cells in each row. Can anyone suggest a method?

David Arenburg
  • 89,637
  • 17
  • 130
  • 188
Sabhijiit
  • 35
  • 1
  • 2
  • 11

2 Answers2

1

You could try apply() with the function sum:

df$v5 <- apply(df,1,sum)
> df
#  v1 v2 v3 v4 v5
#1  1  2  3  6 12
#2  4  5  6 15 30

Here the value of the second parameter in apply(), 1, indicates that the sum should be performed for each row of the dataframe.

data

df <- read.table(text="v1 v2 v3 v4
                        1  2  3  6 
                        4  5  6  15", header=T)
RHertel
  • 22,694
  • 5
  • 36
  • 60
0

Perhaps

T <- cbind(T,rowSums(T))

if T is the table.

mra68
  • 2,950
  • 1
  • 8
  • 17