Can I impute a variable conditional on another? - stata

I am trying to impute the data about whether someone is born in the UK from wave 1 to wave 2. I suspect the egen function would work but I am not sure what the code would look like?
As you can see, I need to assign the same born in the uk response for person id 1 in wave 1 to wave 2.
I know I could do it by reshaping the dataset to a wide format but do you know whether there is any other way?

This is a Stata FAQ as accessible here.
You can copy downwards in the dataset without creating any new variables.
bysort id (wave) : replace born_in_uk = born_in_uk[_n-1] if missing(born_in_uk)
mipolate (SSC) has a groupwise option that checks for there being more than one non-missing value. Search within www.statalist.org for mentions.
Note that egen is a command, not a function.

I am not sure whether here born in the UK is numeric with labels or string. But, what if you would do something like:
encode born_in_UK, gen(born_num)
bysort person_id: egen born_num2=mean(born_num)
drop born_num
rename born_num2 born_num
The idea is to think of the repeating personal ids as groups and use the mean function to fill the missing values in the group. I think this should work.

Related

Removing characters before a certain value in variable names in stata

EDIT: the issue with this question was resolved as Stata changed the variable names in Excel to variable "labels" upon importing the data, and generated the variable "names" that I needed automatically. So the question is unnecessary.
I have a dataset in Stata that has a handful of variable names, some of which begin with a number and a period. Like so:
name of car 62. color of car 145. year of sale state of sale
Accord Red 1995 GA
Corvette Pink 2010 FL
...
How can I remove the numbers from the variable names that contain them so that I wind up with:
name of car color of car year of sale state of sale
Accord Red 1995 GA
Corvette Pink 2010 FL
...
I have some familiarity with the substr() function, but I am confused by the fact that the character count that I need to remove from is not consistent. Instead, I need to remove everything from the period following the number, back.
All those "names" are illegal as variable names, because Stata variable names just can't include spaces or periods or start with a number.
So either your Stata is corrupted beyond belief or you're misunderstanding what you have.
My best guess is that you have read in metadata so that text that could and should be variable labels is in fact making up the first observation (row) in your dataset. If so, the best advice is to go back and repeat the import so that metadata is not read into the dataset. The commands concerned have options to choose that.
In any case, it is immensely better to show data examples using dataex: see the tag wiki for Stata.

Create link between observations clustered within village

Hi I am trying to create dyad from households id clustered within villages with stata. My problem is I do not know how to use vlookup in order to have a list of households id linked to every household.
Without a bit more information this question is tough to answer, but some places you can look are first tabulate to see your data broken down by variables. Another place to check is the bysort and gen commands, these together will probably be the answer you're looking for, although it is tough to tell from the question. Finally, you may want to look into encode if your village variable is a string, you will get a unique id for each village using that command.

how to use tsrevar to create lag variable using stata

I got a panel data (time: date name: ticker). I want to create upto 10 lagged variables for x. So I use the following code.
tsrevar L(1/10).x
rename (`r(varlist)') x_#, addnumber
Because my data is in hourly frequency, and only observation during the daytime. Using the code above, the first observation for each trading day is missing.
My alternative solution is:
by ticker: gen lag1 = return[_n-1]
Then, I have to copy and paste this code 10 times, which looks very messy. Could anyone teach me how to solve this problem please
This is my "10-minute guess" given I don't actually work with anything finer than a daily periodicity.
Stata has no hourly display format that I know of. One way to achieve what you want is using the delta() option when you tsset the data.
clear
set more off
*----- example data -----
// an "hour-by-hour" time series which really has millisecond format
set obs 25
gen double t = _n*1000*60
format %tcDDmonCCYY_HH:MM:SS:.sss t
set seed 3129745
gen ret = runiform()
list, sep(0)
*----- what you want? -----
// 1000*60 milliseconds conform 1 hour
tsset t, delta((1000*60))
// one way
tsrevar L(1/2).ret
rename (`r(varlist)') ret_#, addnumber
// two other ways
gen ret1 = L.ret
gen ret11 = ret[_n-1]
// check
assert ret_1 == ret1
assert ret_1 == ret11
list, sep(0)
tsset also has a generic option, and delta() itself has several specifications. Take a look and test, to see if you find a better fit.
(You mention an "hourly frequency" but you don't give example data with the specifics. There really is no way to know for sure what you're dealing with.)

Stata: Newvar for multiple equal dates

I have trouble to generate a new variable which will be created for every month while having multiple entries for every month.
date1 x b
1925m12 .01213 .323
1925m12 .94323 .343
1926m01 .34343 .342
Code would look like this gen newvar = sum(x*b) but I want to create the variable for each month.
What I tried so far was
to create an index for the date1 variable with
sort date1
gen n=_n
and after that create a binary marker for when the date changes
with
gen byte new=date1!=date[[_n-1]
After that I received a value for every other month but I m not sure if this seems to be correct or not and thats why I would like someone have a look at this who could maybe confirm if that should be correct. The thing is as there are a lot of values its hard to control it manually if the numbers are correct. Hope its clear what I want to do.
Two comments on your code
There's a typo: date[[_n-1] should be date1[_n-1]
In your posted code there's no need for gen n = _n.
Maybe something along the lines of:
clear
set more off
*-----example data -----
input ///
str10 date1 x b
1925m12 .01213 .323
1925m12 .94323 .343
1926m01 .34343 .342
end
gen date2 = monthly(date1, "YM")
format %tm date2
*----- what you want -----
gen month = month(dofm(date2))
bysort month: gen newvar = sum(x*b)
list, sepby(month)
will help.
But, notice that the series of the cumulative sum can be different for each run due to the way in which Stata sorts and because month does not uniquely identify observations. That is, the last observation will always be the same, but the way in which you arrive at the sum, observation-by-observation, won't be. If you want the total, then use egen, total() instead of sum().
If you want to group by month/year, then you want: bysort date2: ...
The key here is the by: prefix. See, for example, Speaking Stata: How to move step by: step by Nick Cox, and of course, help by.
A major error is touched on in this thread which deserves its own answer.
As used with generate the function sum() returns cumulative or running sums.
As used with egen the function name sum() is an out-of-date but still legal and functioning name for the egen function total().
The word "function" is over-loaded here even within Stata. egen functions are those documented under egen and cannot be used in any other command or context. In contrast, Stata functions can be used in many places, although the most common uses are within calls to generate or display (and examples can be found even of uses within egen calls).
This use of the same name for different things is undoubtedly the source of confusion. In Stata 9, the egen function name sum() went undocumented in favour of total(), but difficulties are still possible through people guessing wrong or not studying the documentation really carefully.

How do I get a group minimum over level combinations of factors?

I would like to find minimum values within groups. In stata, I think it is simply "by group, sort : egen minvalue=min(value)"...
I tried to mess around with ave and rowsum, but to no avail.
ave(value, group, FUN=min) did not work.
Sorry this answer is a little late but, in case you are still looking for the answer or for future searchers here goes....
You are onto the right track with the -by- command. Here is what I'd do to find the lowest price of cars in the auto.dta dataset by domestic/foreign grouping.
sysuse auto, clear
bysort foreign : egen minprice = min(price)
What this does is create a new variable 'minprice' that holds the minimum price for domestic cars if a given car (observation) is domestic and vice versa for foreign cars. So this new variable with have just two values in this example and you can check that by doing:
tabulate minprice
Depending on why you wanted to find the minimum values by group this may not be what you had in mind but hopefully someone finds it helpful.