Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 对第一个子集类别执行减法_R_Dplyr_Data.table - Fatal编程技术网

R 对第一个子集类别执行减法

R 对第一个子集类别执行减法,r,dplyr,data.table,R,Dplyr,Data.table,这是我的数据 structure(list(code = c(11202L, 11202L, 11202L, 11202L, 11202L, 11202L, 11202L), date = structure(1:7, .Label = c("2017-08-20 00:00:00.000", "2017-08-21 00:00:00.000", "2017-08-22 00:00:00.000", "2017-08-24 00:00:00.000", "2017-08-25 00:00:

这是我的数据

structure(list(code = c(11202L, 11202L, 11202L, 11202L, 11202L, 
11202L, 11202L), date = structure(1:7, .Label = c("2017-08-20 00:00:00.000", 
"2017-08-21 00:00:00.000", "2017-08-22 00:00:00.000", "2017-08-24 00:00:00.000", 
"2017-08-25 00:00:00.000", "2017-08-27 00:00:00.000", "2017-08-28 00:00:00.000"
), class = "factor"), x1 = c(4L, 3L, 2L, 15L, 20L, 15L, 10L), 
    action = c(0L, 0L, 1L, 1L, 1L, 1L, 1L), x2 = c(4L, 3L, 0L, 
    12L, 17L, 12L, 7L)), .Names = c("code", "date", "x1", "action", 
"x2"), class = "data.frame", row.names = c(NA, -7L))
我需要第一类的行动专栏, 减去x1-x2,结果显示为“基本列”。 零动作类别的值只是从x2复制到base中, 他们没有算计

如此理想的输出

code    date                    x1   action x2  base
11202   2017-08-20 00:00:00.000 4   0        4  4
11202   2017-08-21 00:00:00.000 3   0        3  3
11202   2017-08-22 00:00:00.000 2   1        0  2
11202   2017-08-24 00:00:00.000 15  1        12 3
11202   2017-08-25 00:00:00.000 20  1        17 3
11202   2017-08-27 00:00:00.000 15  1        12 3
11202   2017-08-28 00:00:00.000 10  1         7 3

怎么做?

非常简单

df <- df 
    %>% mutate(base = ifelse(action > 0,x1-x2,x2))
df%突变(base=ifelse(action>0,x1-x2,x2))

检查动作是否大于0,如果大于0,则从x1中减去x2,否则将x2原封不动地传递。

非常简单

df <- df 
    %>% mutate(base = ifelse(action > 0,x1-x2,x2))
df%突变(base=ifelse(action>0,x1-x2,x2))

检查动作是否大于0,如果大于0,则从x1中减去x2,否则将x2不变地传递。

类似于
df$what=ifelse(df$action==1,df$x1 df$x2,df$base)
?@user2974951,是的,它的工作方式类似于
df$what=ifelse(df$action==1,df$x1 df df$x2,df$base)
?@user2974951,是的,它可以工作