R?中一个data.frame的每个变量的累积和。

In my code below, I want to first remove the Variable for which i do not have any value (Ie., F should be removed where all the values are 'NA'). then i am trying to find accumulated values of each Variable. I tried with the following code but i am not getting anything out of it.

library(tidyverse)

set.seed(50)

DF <- data.frame(Days = 1:5, A = runif(5,0,3), S = runif(5,1,6),  F = matrix(NA, 5,1), C = runif(5,2,4))
DF_1 <- gather(DF, -Days, key = "Variable", value = "Value")
DF_2 <- DF_1 %>% 
  filter(Variable == "NA") %>% 
  mutate(cumulative_Sum = cumsum(Value))

输出量

For Variable A I should get something like below- similar for others

> A <- cumsum(DF$A)
> A
[1] 2.126181 3.439161 4.039176 6.340374 7.879859
评论
也,許
也,許

After grouping by 'Variable', filter out the groups having all NA 'Value', then do the cumulative sum of 'Value' after replacing the NA with 0

library(dplyr)
library(tidyr)
DF_1 %>%           
   group_by(Variable) %>% 
   filter(!all(is.na(Value))) %>% 
   mutate(Value = cumsum(replace_na(Value, 0)))
# A tibble: 15 x 3
# Groups:   Variable [3]
#    Days Variable Value
#   <int> <chr>    <dbl>
# 1     1 A         2.13
# 2     2 A         3.44
# 3     3 A         4.04
# 4     4 A         6.34
# 5     5 A         7.88
# 6     1 S         1.22
# 7     2 S         5.72
# 8     3 S         9.95
# 9     4 S        11.2 
#10     5 S        12.7 
#11     1 C         2.78
#12     2 C         5.32
#13     3 C         8.60
#14     4 C        10.8 
#15     5 C        13.3 

If we use the 'wide' format 'DF', then use mutate_at

DF %>%
   mutate_at(-1, cumsum)
点赞
评论