lundi 30 juillet 2018

Subtract one column from others based on successive conditions

I have a df as follows. I would like to subtract col y from the other columns using the following rules:

  • No result can be negative
  • If y can be divided equally and subtracted across from a:c without generating a negative, then subtract an equal amount across cols
  • else, if y can be divided and subtracted equally from b:c and the remainder from a without generating a negative, then subtract from cols
  • else, if y can be subtracted from c, the remainder from b, and the subsequent remainder from a without generating a negative, then subtract from cols
  • else, if y can be subtracted from from b and the remainder from a without generating a negative, then subtract from cols
  • else, subtract from a

df:

structure(list(a = c(0, 6.22, 1.2, 0.22, 0.24), b = c(8.88, 1.08, 
0.25, 0, 0), c = c(13.76, 0, 19.61, 0, 0), d = c(-2.64, -0.3, 
-11.06, -0.22, -0.24)), .Names = c("a", "b", "c", "d"), row.names = c(NA, 
-5L), class = c("tbl_df", "tbl", "data.frame"), spec = structure(list(
    cols = structure(list(a = structure(list(), class = c("collector_double", 
    "collector")), b = structure(list(), class = c("collector_double", 
    "collector")), c = structure(list(), class = c("collector_double", 
    "collector")), d = structure(list(), class = c("collector_double", 
    "collector"))), .Names = c("a", "b", "c", "d")), default = structure(list(), class = c("collector_guess", 
    "collector"))), .Names = c("cols", "default"), class = "col_spec"))

starting table:

a     b     c      d
0     8.88  13.76  -2.64
6.22  1.08  0      -0.3
1.2   0.25  19.61  -11.06
0.22  0     0      -0.22
0.24  0     0      -0.24

desired result:

a     b     c      d
0     6.24  11.12  -2.64
6.22  0.78  0      -0.3
1.2   0.25  8.55   -11.06
0     0     0      -0.22
0     0     0      -0.24

Aucun commentaire:

Enregistrer un commentaire