Home > Enterprise >  How to calculate with rows in a column in R
How to calculate with rows in a column in R

Time:10-10

I am trying to do calculations with rows in a column: I have the following data for one product:

Day    Price
1      3$
2      12$
3      4$
4      2$
5      4$

I want to divide the price change of a day by the day before so, for example for Day 2:

12$/3$ = 4 

Results should be:

Day    Price    Calculation
1      3$       NA
2      12$      4
3      4$       0,33
4      2$       0,5
5      4$       2

I have a list of 5000 prices. I am also concerned how to get the NA in Day 1 were no calculation is possible.

Thank you!

CodePudding user response:

We may divide the current value by the previous value (lag). The $ is not considered in the numeric class. We may need to extract the numeric value (parse_number) does that and do the calculation

library(dplyr)
df1 <- df1 %>%
    mutate(Calculation = readr::parse_number(as.character(Price)),
        Calculation = round(Calculation/lag(Calculation), 2))

-output

df1
 Day Price Calculation
1   1    3$          NA
2   2   12$        4.00
3   3    4$        0.33
4   4    2$        0.50
5   5    4$        2.00

data

df1 <- structure(list(Day = 1:5, Price = c("3$", "12$", "4$", "2$", 
"4$")), class = "data.frame", row.names = c(NA, -5L))

CodePudding user response:

Here is dplyr only solution using gsub instead of parse_number:

library(dplyr)
df %>% 
  mutate(Calculation=as.numeric(gsub("\\$", "", Price)),
         Calculation=round(Calculation/lag(Calculation), 2))
Day Price Calculation
1   1    3$          NA
2   2   12$        4.00
3   3    4$        0.33
4   4    2$        0.50
5   5    4$        2.00
  • Related