I have a dataset that looks like this.
bankname bankid year totass cash bond loans Bank A 1 1881 244789 7250 20218 29513 Bank B 2 1881 195755 10243 185151 2800 Bank C 3 1881 107736 13357 177612 NA Bank D 4 1881 170600 35000 20000 5000 Bank E 5 1881 3200000 351266 314012 NA
and I want to calculate some ratios based on bank balances. and I want the data set to look like this
bankname bankid year totass cash bond loans CashtoAsset BondtoAsset LoanstoAsset Bank A 1 1881 2447890 7250 202100 951300 0.002 0.082 0.388 Bank B 2 1881 195755 10243 185151 2800 0.052 0.945 0.014 Bank C 3 1881 107736 13357 177612 NA 0.123 1.648585431 NA Bank D 4 1881 170600 35000 20000 5000 0.205 0.117 0.029 Bank E 5 1881 32000000 351266 314012 NA 0.0109 0.009 NA
Here is the code for data replication
bankname <- c("Bank A","Bank B","Bank C","Bank D","Bank E") bankid <- c( 1, 2, 3, 4, 5) year<- c( 1881, 1881, 1881, 1881, 1881) totass <- c(244789, 195755, 107736, 170600, 32000000) cash<-c(7250,10243,13357,35000,351266) bond<-c(20218,185151,177612,20000,314012) loans<-c(29513,2800,NA,5000,NA) bankdata<-data.frame(bankname, bankid,year,totass, cash, bond, loans)
Firstly, I got rid of the NS in the balance sheets.
cols <- c("totass", "cash", "bond", "loans") bankdata[cols][is.na(bankdata[cols])] <- 0
Then i calculate the odds
library(dplyr) bankdata<-mutate(bankdata,CashtoAsset = cash/totass) bankdata<-mutate(bankdata,BondtoAsset = bond/totass) bankdata<-mutate(bankdata,loanstoAsset =loans/totass)
But instead of calculating all these relationships line by line, I want to create a view to do it all at once. In Stata, I would do
foreach x of varlist cash bond loans { by bankid: gen `x'toAsset = `x'/ totass }
How can I do it?