-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
  • 91,361
  • 17
  • 137
  • 196
Sabhijiit
  • 55
  • 1
  • 2
  • 12

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
  • 23,412
  • 5
  • 38
  • 64
0

Perhaps

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

if T is the table.

mra68
  • 2,960
  • 1
  • 10
  • 17