HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Lookup GINI by year and country

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
yearcountryginiandlookup

Problem

This takes a dataframe as an argument, looks at all pairs of two columns in that data frame (country and year) and returns a column value of that pair in another data frame (the gini number).

get_gini <- function(year, country){
    GINI = 0
    SUBSETTED_WITH_COUNTRY_NAME_NOW_WITH_YEAR <- inequality[inequality$Code== country & inequality$Year== year,]
    GINI <- mean(as.numeric(SUBSETTED_WITH_COUNTRY_NAME_NOW_WITH_YEAR$Gini))

    country_and_year<- totes_data[totes_data$totes_data == country & totes_data$year == year,] 
    country_and_year$GiniState1<-GINI
    output<-country_and_year$GiniState1
    output<-output[1]
    if (is.na(output)){
      output=0
    }
    else {
      output = output
    }
    assign("ginilist",output, envir=globalenv())
    rbind(output,ginilist)
}

Solution

With the data.table package, you can do a quick join and get the gini coefficient much easier. This solution is also vectorized, so you can call it with something like gini(2000:2004, 'USA') to get the gini coefficients for the USA for years 2000-2004.

It is also good practice to include the data in your function call, so you don't use objects from the global environment within the function call. This function outputs the entire data.table, but you can also just use the gini coefficient as output, if you add [, GINI] at the end.

gini <- function(year, country, data = inequality){
  require(data.table)
  setkey(setDT(data), 'Code', 'Year')[J(Code = country, Year=year), 
                                        list(GINI = mean(as.numeric(Gini))), 
                                        by=list(Code, Year)]
}

Code Snippets

gini <- function(year, country, data = inequality){
  require(data.table)
  setkey(setDT(data), 'Code', 'Year')[J(Code = country, Year=year), 
                                        list(GINI = mean(as.numeric(Gini))), 
                                        by=list(Code, Year)]
}

Context

StackExchange Code Review Q#78495, answer score: 3

Revisions (0)

No revisions yet.