I cannot get the foreach command to work to calculate running sums for several variables. Any help would be highly appreciated.
I have data for many companies from 1980 through 2022 and 249 countries (abbreviated using ISO2 codes). I want to calculate the running sums for every country. The command bysort company (year): gen sum_AF = sum(AF) and so on, for each country, works fine. But I cannot get the command to work using the foreach variable. What am I doing wrong?
vl create countrylist = (AF-ZW)
foreach var in countrylist {
bysort company (year): gen cum_'var' = sum('var')
}
. dataex company year AF AX AL ZW
----------------------- copy starting from the next line -----------------------
I have data for many companies from 1980 through 2022 and 249 countries (abbreviated using ISO2 codes). I want to calculate the running sums for every country. The command bysort company (year): gen sum_AF = sum(AF) and so on, for each country, works fine. But I cannot get the command to work using the foreach variable. What am I doing wrong?
vl create countrylist = (AF-ZW)
foreach var in countrylist {
bysort company (year): gen cum_'var' = sum('var')
}
. dataex company year AF AX AL ZW
----------------------- copy starting from the next line -----------------------
Code:
* Example generated by -dataex-. For more info, type help dataex clear input str4 company float(year AF AX AL ZW) "SAIC" 1980 0 0 0 0 "SAIC" 1981 0 0 0 0 "SAIC" 1982 0 0 0 0 "SAIC" 1983 0 0 0 0 "SAIC" 1984 0 0 0 0 "SAIC" 1985 0 0 0 0 "SAIC" 1986 0 0 0 0 "SAIC" 1987 0 0 0 0 "SAIC" 1988 0 0 0 0 "SAIC" 1989 0 0 0 0 "SAIC" 1990 0 0 0 0 "SAIC" 1991 0 0 0 0 "SAIC" 1992 0 0 0 0 "SAIC" 1993 0 0 0 0 "SAIC" 1994 0 0 0 0 "SAIC" 1995 0 0 0 0 "SAIC" 1996 0 0 0 0 "SAIC" 1997 0 0 0 0 "SAIC" 1998 0 0 0 0 "SAIC" 1999 0 0 0 0 "SAIC" 2000 0 0 0 0 "SAIC" 2001 0 0 0 0 "SAIC" 2002 0 0 0 0 "SAIC" 2003 0 0 0 0 "SAIC" 2004 0 0 0 0 "SAIC" 2005 0 0 0 0 "SAIC" 2006 0 0 0 0 "SAIC" 2007 0 0 0 0 "SAIC" 2008 0 0 0 0 "SAIC" 2009 0 0 0 0 "SAIC" 2010 0 0 0 0 "SAIC" 2011 0 0 0 0 "SAIC" 2012 0 0 0 0 "SAIC" 2013 0 0 1 0 "SAIC" 2014 0 0 0 0 "SAIC" 2015 0 0 0 0 "SAIC" 2016 0 0 0 0 "SAIC" 2017 0 0 0 0 "SAIC" 2018 0 0 0 0 "SAIC" 2019 0 0 0 0 "SAIC" 2020 0 0 0 0 "SAIC" 2021 1 0 1 1 "SAIC" 2022 0 0 0 0 end
Comment