Calculating new column in a data frame

I have this dataframe with 5 column where stock is the current_stock. And i want a new column stock_over_time which is then calculated as stock_over_time = stock - sales + purchase.

df=tibble(article=rep("article one",5), 
week=c(1,2,3,4,5), 
sales=10, 
purchase=c(5,0,5,5,0), 
stock=c(50))

# A tibble: 5 x 5
  article      week sales purchase stock
  <chr>       <dbl> <dbl>    <dbl> <dbl>
1 article one     1    10        5    50
2 article one     2    10        0    50
3 article one     3    10        5    50
4 article one     4    10        5    50
5 article one     5    10        0    50

My final dataframe should look like this:

# A tibble: 5 x 5
  article      week sales purchase stock stock_over_time
  <chr>       <dbl> <dbl>    <dbl> <dbl>  <dbl>
1 article one     1    10        5    50     NA
2 article one     2    10        0    50     45
3 article one     3    10        5    50     35
4 article one     4    10        5    50     30
5 article one     5    10        0    50     25

...where stock_over_time is calculated as:

50 - 10 + 5 = 45
45 - 10 + 0 = 35
35 - 10 + 5 = 30
30 - 10 + 5 = 25

How would i do this?

Hello Lukr90,
Hope this help you :

df=tibble(article=rep("article one",5),
week=c(1,2,3,4,5),
sales=10,
purchase=c(5,0,5,5,0),
stock=c(50))

stock_over_time = c(50, 45, 35, 30) - df$sales[2:5] + df$purchase[1:4]
stock_over_time = c(NA, stock_over_time)
df = as.tibble(cbind(df, stock_over_time))
df

Have a nice day :grinning:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.