Skip to content

Instantly share code, notes, and snippets.

@druedin
Last active October 30, 2023 21:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save druedin/081458f3cf8d135883b723dbc393e9e2 to your computer and use it in GitHub Desktop.
Save druedin/081458f3cf8d135883b723dbc393e9e2 to your computer and use it in GitHub Desktop.
That quadruple sapply()
# Hi Glen. Here it comes:
countries <- unique(country)
everything <- sapply(countries, function(cy) {
parties <- unique(party[country==cy]) # all parties
this <- sapply(parties, function(z) sapply(1990:2013, function(y) mav(as.numeric(sapply(seq(y-3,y+3), function(x) experts.raw[country==cy & party==z & year==x])))))
rownames(this) <- 1990:2013
colnames(this) <- parties
return(this)
})
print(everything )
# >> mav() is a moving average function. I have wrapped it into an sapply() at the time to get the seven years in my dataset separately.
mav <- function(x,k=3){
n <- length(x)
return(sapply((k+1):(n-k), function(i) sum(x[(i-k):(i+k)],na.rm=TRUE)/(2*k+1-sum(is.na(x[(i-k):(i+k)])))))
}
# >> The dataset consists of several columns, of which "country", "year", "party", and "expert.raw" are relevant. In the "expert.raw" we have the party position from an expert survey, the other three columns identify the country, year, and party. There are plenty of missing values because we do not have expert estimates for all the elections.
# >> In the first sapply(), I basically ask R to run the code for each of the countries
# >> In the second sapply(), I ask R to run the code for each party in a country
# >> In the third sapply(), I ask R to run the code for each year (for a given party in a given country).
# >> The fourth sapply() feeds the existing expert estimates for the year examined +/- 3 years (i.e. 7 years) and calculates the moving average on that.
# >> After closing all the relevant brackets, I just label the column and row names
# >> The resulting object "everything" is a list of 8 (countries) with a column for each party in a country and the years 1990 to 2013. The cells give the moving average of the expert positions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment