将多列相加为-1,0,1

时间:2015-06-09 05:54:40

标签: r matrix dataframe

我尝试创建一种将Total列更改为-1,1或0的简单方法。当x = 1,y = 1,z = 1时,则Total = 1。当x = -1,y = 1,z = 1时,则Total = -1。在所有其他情况下,总计= 0。因此,行2013-07-03和2013-07-05应该具有Total = 1。行2013-07-09应该有Total = -1。所有其他行应该具有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 个答案:

答案 0 :(得分:2)

产品可以这样计算:

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

答案 1 :(得分:2)

如果有多列,请尝试

 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

数据

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"))