I am slowly moving from Excel to R but keep running into problems with tasks that would take me two seconds to do in Excel... For instance, see the following example of data which is GDP in France and UK:
Let imagine I would like to calculated percent change from the 1929, which is the Great Depression. In Excel I would do something like this in a new column for France: =(B2/$B$11)*100 and then fill the formula down to the adjacent cells. And then, repeat for UK.
How would you do this in R (note, this is just an example. I am interested in the thought process behind)? Obviously, the data would be structured differently with three variables: year, country, gdp.
I am thinking about using mutate() and then case_when() to pin point the right country. But this is where I get stuck. Have a look at my code. Data is Maddison:
library(tidyverse)
library(ggplot2)
library(haven)
library(readxl)
# Loading df
df <- read_excel("/PATH TO DATA/mpd2018.xlsx", sheet = 2)
# Tidy dataset
df <- df %>%
transmute(
cntry = as_factor(countrycode), # Rename and define as factor
year = zap_labels(year), # Zap labels
gdp = zap_labels(rgdpnapc) # Rename and zap labels
) %>%
dplyr::filter(
cntry %in% c("FRA","GBR"), # Keep only FRA and GRB
year >= 1920 & year <= 1950 # Only the interval between 1920 and 1950
)
# Calculations
df <- df %>% mutate(
gdp_rel = case_when(
cntry == "FRA" ~ (df$gdp/df[10,3])*100,
cntry == "GBR" ~ (df$gdp/df[41,3])*100
))
First of all, the code produces an error. But more importantly, I believe it can be done smarter than pin-pointing by df[x, y]. What is the data frame was much bigger?
