Create and add a new variable with the pipe operator = Create a Plot out of it

Viewed 346

I want to create and add a new variable called "XY" by multiplying the capital income of several countries by 1000 and then divide it by its population = gdp*1000/pop. Afterwards I want to make a plot with selecting the years and countries (Here I want to select certain countries from the data, e.g. Turkey, France, Germany and the timeframe should be 1996 and later meaning 1997, 1998 etc.), where I want to have the x-axis with years and the y-axis with capital income. I want to have every country in a different colour. How can I put this in a R-code. My start so far is like this:

  > # two pipes
  > gapminder %>%
  +     select(Germany, Italy, France) %>%
  +     select(population >= 1996)

  plot(eu_macro$germany, eu_macro$turkey, eu_macro$france, gdp_capita$medv, main = "GDP 
  development", xlab = "Year", ylab = "gdp_capita")

Sorry, I am very new to R and Coding in general and just hope to get an understanding for it for Finance classes.

1 Answers

Ary you looking for such a solution?

library(gapminder)
library(tidyverse)
gapminder %>%
    mutate(XY = gdpPercap*1000/pop) %>% 
    filter(country=="Germany" | 
           country=="Turkey"|
           country=="France") %>%
    filter(year >= 1996) %>% 
    ggplot(aes(x=factor(year), y=XY, fill=country)) +
    geom_col(position = "dodge") +
    ggtitle("GDP development") +
    xlab("Year") + ylab("gdp_capita")

enter image description here

Related