Summing multiple columns to equal -1,0,1

58 views Asked by At

I'm trying to create a simple way to change the Total column to either -1, 1, or 0. When x=1, y=1, z=1, then Total=1. When x=-1, y=1, z=1, then Total=-1. In all other cases, Total=0. So, rows 2013-07-03 and 2013-07-05 should have Total=1. Row 2013-07-09 should have Total=-1. All other rows should have Total=0.

             x   y   z  Total
2013-07-01   1   1   0    0
2013-07-02   1   0   0    0
2013-07-03   1   1   1    1
2013-07-05   1   1   1    1
2013-07-08   0   0   1    0
2013-07-09  -1   1   1   -1
2

There are 2 answers

0
bgoldst On BEST ANSWER

The product can be calculated thusly:

df <- data.frame(x=c(1,1,1,1,0,-1), y=c(1,0,1,1,0,1), z=c(0,0,1,1,1,1), Total=c(2,1,3,3,1,2), row.names=c('2013-07-01','2013-07-02','2013-07-03','2013-07-05','2013-07-08','2013-07-09') );
df$Total <- df$x*df$y*df$z;
df;
##             x y z Total
## 2013-07-01  1 1 0     0
## 2013-07-02  1 0 0     0
## 2013-07-03  1 1 1     1
## 2013-07-05  1 1 1     1
## 2013-07-08  0 0 1     0
## 2013-07-09 -1 1 1    -1
0
akrun On

If there are multiple columns, try

 df$Total <- Reduce(`*`, df[1:3])

 df
 #            x y z Total
 #2013-07-01  1 1 0     0
 #2013-07-02  1 0 0     0
 #2013-07-03  1 1 1     1
 #2013-07-05  1 1 1     1
 #2013-07-08  0 0 1     0
 #2013-07-09 -1 1 1    -1

data

df <- structure(list(x = c(1L, 1L, 1L, 1L, 0L, -1L), y = c(1L, 0L, 
1L, 1L, 0L, 1L), z = c(0L, 0L, 1L, 1L, 1L, 1L), Total = c(2L, 
1L, 3L, 3L, 1L, 2L)), .Names = c("x", "y", "z", "Total"),
class =     "data.frame", row.names = c("2013-07-01", 
"2013-07-02", "2013-07-03", "2013-07-05", "2013-07-08", "2013-07-09"))