Heads or Tails of your dta

August 25, 2010 at 4:44 am 5 comments

| Gabriel |

A lot of languages (e.g., Bash and R) offer the commands/functions “head” and “tail.” These show you the first or last 5 or 10 things in a file or object. “Head” is similar to typing “list in 1/10” in Stata and you’d do so for similar reasons. Because I’m getting used to the Unix version, I wrote an ado file that lets “head” and “tail” work in Stata. Note that these Stata programs only work on the master dataset and can’t also be applied to using datasets or output like they can in Unix.

Update: see the comments for some suggestions on how to work in error messages and the like.

capture program drop head
program define head
	if [_N]<10 {
		local ten = [_N]
	}
	else {
		local ten 10
	}
	syntax [varlist(default=none)]
	list `varlist' in 1/`ten'
end

capture program drop tail
program define tail
	syntax [varlist(default=none)]
	local theend = [_N]
	local theend_min10 = [_N]-10
	if `theend_min10'<1 {
		local theend_min10 1
	}
	list `varlist' in `theend_min10'/`theend'
end

*have a nice day

Entry filed under: Uncategorized. Tags: .

Blogola Newsola

5 Comments

  • 1. statauser  |  August 25, 2010 at 8:41 am

    In the -head- command you have to define the local macro `ten’ for the cases where _N >= 10. Simply add the following line at the beginning:

    local ten = 10

    • 2. gabrielrossman  |  August 25, 2010 at 10:05 am

      thanks, i updated the post to correct the bug

  • […] very simply into a longitudinal format with countries as the cross-sectional identifier. The head of this data would look something like […]

  • 4. Nick Cox  |  August 27, 2010 at 12:50 pm

    Stata allows -in L- or -in l- for specifying the last observation and negative observation numbers that count backwards from the end of the data. Also, although it is futile, you can trap the case of no data a little more elegantly. Here is another version of -tail-. Another version of -head- could be written in similar style.

    program tail  
    	version 8.2 
    	syntax [varlist(default=none)]  
    	if c(N) == 0 error 2000 
    	else { 
    		local start = min(10, c(N)) 
    		list `varlist' in -`start'/L  
    	}
    end

    [note, gabriel took the liberty of adding the “pre” html tags, other than that the comment is unchanged]

    • 5. gabrielrossman  |  August 27, 2010 at 2:18 pm

      thanks much, that’s better. for the benefit of other readers, the “in F/L” syntax Professor Cox is using is described in the documentation at [U] 11.1.4

      here’s the rewritten head command, following the model of his tail command

      program head
      	version 8.2
      	syntax [varlist(default=none)]
      	if c(N) == 0 error 2000
      	else {
      		local start = min(10, c(N))
      		list `varlist' in F/+`start'
      	}
      end

The Culture Geeks


%d bloggers like this: