Suusie
Suusie

Reputation: 149

Caculate number by adding up value from the previous row over multiple columns in r

I have a sample dataframe from which I want to calculate a value by adding up the previous value over multiple columns.

I have a dataframe df:

LK   Loc1  Loc2  Loc3    
1     13   22     0          
2     20   18     4          
3     12   21     2          
4     2     0     1          
5     1     2     0 

I want to get in a new dataframe:

 LK   Loc1  Loc2  Loc3    
  1     13   22     0          
  2     33   40     4          
  3     45   61     6          
  4     47   61     7          
  5     48   63     7

I tried something with:

df2 <- df %>% 
  mutate_at(vars(-LK), accumulate(function(.) (.) * 0.99))

But I can't get it to work.

Any help is appreciated.

Thank you in advance

Upvotes: 3

Views: 176

Answers (3)

jpdugo17
jpdugo17

Reputation: 7106

library(tidyverse)

df1 <- read_table('LK   Loc1  Loc2  Loc3    
1     13   22     0          
2     20   18     4          
3     12   21     2          
4     2     0     1          
5     1     2     0 ')

df1[-1] %>%
    map_df(~ cumsum(.x)) %>%
    {bind_cols(df1[1], .)}
#> # A tibble: 5 x 4
#>      LK  Loc1  Loc2  Loc3
#>   <dbl> <dbl> <dbl> <dbl>
#> 1     1    13    22     0
#> 2     2    33    40     4
#> 3     3    45    61     6
#> 4     4    47    61     7
#> 5     5    48    63     7

#without formula synthax in map_df

df1[-1] %>%
    map_df(cumsum) %>%
    {bind_cols(df1[1], .)}
#> # A tibble: 5 x 4
#>      LK  Loc1  Loc2  Loc3
#>   <dbl> <dbl> <dbl> <dbl>
#> 1     1    13    22     0
#> 2     2    33    40     4
#> 3     3    45    61     6
#> 4     4    47    61     7
#> 5     5    48    63     7

Created on 2021-06-21 by the reprex package (v2.0.0)

Upvotes: 3

Anoushiravan R
Anoushiravan R

Reputation: 21908

You can use this but this is just a simple accumulation and you can use cumsum instead as specified by dear @MrFlick:

library(dplyr)
library(dplyr)

DF %>% 
  map_at(-1, ~ accumulate(.x, `+`)) %>%
  bind_cols()

     LK  Loc1  Loc2  Loc3
  <int> <int> <int> <int>
1     1    13    22     0
2     2    33    40     4
3     3    45    61     6
4     4    47    61     7
5     5    48    63     7

Upvotes: 2

akrun
akrun

Reputation: 886948

We can use + in accumulate

library(dplyr)
library(purrr)
df %>% 
    mutate(across(-LK, ~ accumulate(., `+`)))

-output

 LK Loc1 Loc2 Loc3
1  1   13   22    0
2  2   33   40    4
3  3   45   61    6
4  4   47   61    7
5  5   48   63    7

If we want to multiply by 0.99

df %>% 
     mutate(across(-LK, ~ accumulate(.,  function(x, y) 
          x + y * 0.99)))

data

df <- structure(list(LK = 1:5, Loc1 = c(13L, 20L, 12L, 2L, 1L),
 Loc2 = c(22L, 
18L, 21L, 0L, 2L), Loc3 = c(0L, 4L, 2L, 1L, 0L)), 
class = "data.frame", row.names = c(NA, 
-5L))

Upvotes: 4

Related Questions