Appreciate any help on this, I'm trying to re-learn some fundamentals.
Here is some sample code to work with for my problem, it is from a database of injured workers.
Area <- c("Connecticut", "Maine", "Massachusetts", "New Hampshire", "Texas", "Arizona", "California", "Washington")
Region <- c("Northeast", "Northeast", "Northeast", "Northeast", "South", "South", "West", "West")
X2004 <- c(0,1,4,1,3,4,2,2)
X2005 <- c(1,0,6,2,0,1,0,2)
X2006 <- c(0,0,1,1,2,1,0,0)
df1 <- data.frame(Area, Region, X2004, X2005, X2006)
I would like to show the percent change from the two-year average of 2004-2005 to the single year 2006 in Base R. I was able to solve this with the tidyverse package, but that feels like using a crutch. Here is what I have so far:
df2 <- reshape(df1,
idvar=c("Area"),
v.names="count",
varying=c("X2004","X2005","X2006"),
direction="long",
times=2004:2006,
timevar="year")
df3 <- df2 %>% group_by(Region, year) %>%
summarise(total_count = sum(count))
df3$pre <- ifelse(df3$year<=2005, 1, 0)
df3 %>%
group_by(Region) %>%
summarise(mean_count_pre = mean(total_count[pre==1]),
mean_count_post = mean(total_count[pre==0]),
pct_change = 100*(mean_count_post - mean_count_pre) / mean_count_pre)
Any ideas on how to tackle this without relying on tidyverse or dplyr? Really appreciate help on this, I learned R in tidyverse, and I'm trying to get a better understanding of the fundamentals.