Use of Loops for Dataframe Editing [R]

Asked

Viewed 57 times

0

I used the package wbstats to download a World Bank Governance Quality database for Latin American countries. The code below reproduces the process:

LATAM <- c("ARG","BOL","BRA","CHL","COL","CRI","CUB","DOM","ECU","GTM","HND","HTI","MEX","NIC","PAN", "PER","PRY","SLV","URY","VEN")

WGI <- c("CC.EST", "GE.EST", "PV.EST", "RQ.EST", "RL.EST", "VA.EST")

WGI_LAT <- wb(country = LATAM, indicator = WGI)

I tried to edit the database using Loops. I made an array and transferred the values of the respective indicators to new columns, as follows:

WGI_LAT <- data.frame(WGI_LAT$country, WGI_LAT$iso3c, WGI_LAT$date, WGI_LAT$indicatorID, WGI_LAT$value)
colnames(WGI_LAT) <- c('Country', 'Country_code', 'Dates', 'WGI', 'Value')

series = c('CC.EST', 'GE.EST', 'PV.EST', 'RQ.EST', 'RL.EST', 'VA.EST')
database = matrix(NA, ncol=length(series), 
             nrow=nrow(WGI_LAT)/length(series))

for(i in 1:length(series)){
  database[,i] = WGI_LAT$Value[WGI_LAT$WGI
                         ==series[i]] 
  database = data.frame(database)
  colnames(database) = series
}

In doing so, I was able to break down the information from the indicators into different columns, but I lost the information from countries and years. Could someone help me figure out a way to edit the base by preserving this information (as seen in the dataframe WGI_LAT), or incorporating them at a later date?

1 answer

0


I solved the problem by combining another data.frame with GDP growth information. By merging the two data.frames, I was able to generate a final data.frame with the information I needed. Below, follow the code:

GDP <- c("NY.GDP.MKTP.KD.ZG")
GDP_LAT <- wb(country = LATAM, indicator = GDP, startdate = 1996, enddate = 2018)
GDP_LAT <- GDP_LAT[,c(2,7,3)]
colnames(GDP_LAT) <- c("Dates", "Country", "GDP")
GDP_Latam <- subset(GDP_LAT, Dates!=1997 & Dates!=1999 & Dates!=2001)

database <- data.frame(GDP_Latam, WGI_Latam)
colnames(database) <- c("Dates", "Country", "GDP", "HDI", "CC", "GE", "PV", "RQ", "RL", "VA")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.