Home > Enterprise >  New column with percentage change in R
New column with percentage change in R

Time:11-23

How do I make a new column in DF with the percentage change in share price over the year?

DF <- data.frame(name = c("EQU", "YAR", "MOWI", "AUSS", "GJF", "KOG", "SUBC"),
                 price20 = c(183, 343, 189, 88, 179, 169, 62),
                 price21 = c(221, 453, 183, 85, 198, 232, 67))

CodePudding user response:

This line should do it:

DF$change <- (DF$price21/DF$price20*100) - 100

CodePudding user response:

We can use a simple division and scales::percent:

library(dplyr)

DF %>% mutate(percent_change = scales::percent((price21-price20)/price20))

  name price20 price21 percent_change
1  EQU     183     221         20.77%
2  YAR     343     453         32.07%
3 MOWI     189     183         -3.17%
4 AUSS      88      85         -3.41%
5  GJF     179     198         10.61%
6  KOG     169     232         37.28%
7 SUBC      62      67          8.06%
  • Related