减法乘法和递归计数

时间:2019-06-20 05:15:16

标签: r

我需要按照以下格式计算减法和乘法的百分比。

df1

A   B   C   D   E
8   4   3   3   8
5   1   6   8   2

预期输出:

                A   B   C   D   E
                8   4   3   3   8
                5   1   6   8   2
COUNT           13  5   9   11  10
COUNT PERCENT   13  5   9   11  10
SUBTRACTION     8   -4  -2  1   10
MULTIPLICATION  104 -20 -18 11  100

1.count will give the number of items in the columns, there can be n number of columns 
2.count percentage
3.subtraction = need to subtraction of count row i.e. 13-5 = 8, 5-9 = -4, 9-11=-2, 10 as it    
4. multiplication  - its a multiplication of count and subtraction rows. 

1 个答案:

答案 0 :(得分:0)

library(dplyr)
df2 <- df %>%
  t() %>%
  as_tibble() %>%
  mutate(count = V1 + V2,
         count_pct = count, # not sure what else expected here
         subtraction = count - lead(count, default = 0),
         multiplication = count * subtraction) %>%
  t()

               [,1] [,2] [,3] [,4] [,5]
V1                8    4    3    3    8
V2                5    1    6    8    2
count            13    5    9   11   10
count_pct        13    5    9   11   10
subtraction       8   -4   -2    1   10
multiplication  104  -20  -18   11  100