1

Can I refer to variables by the number of the column they reside in?


Here's why I want to know: for each observation, I have three vectors in Euclidean space, so my columns are

obsID | v1b1 v1b2 v2b1...v5b4 | tv1b1 tv1b2 tv2b1...tv5b4 | nv1b1 nv1b2 nv2b1...nv5b4

where the | are included simply for readability. My variable names look like those above, but I don't know the naming pattern ahead of time. I can get the length of each vector as ng = (c(k) - 1)/3, so if I could refer to variables by column, it would be straightforward to write a loop to find Euclidean distances, e.g., from v to nv.

I know there are other ways to go about calculating the Euclidean distance (like reshaping the data; or extracting the varnames from 2/(ng+1) and doing a foreach loop on them), but if there is a way to reference variables by column number, I would like to know it.

Frank
  • 66,179
  • 8
  • 96
  • 180
  • 2
    Here is an old [post](http://www.stata.com/statalist/archive/2010-03/msg00073.html) on the topic. The solution is basically retrieving the variable list in its order with `ds`, and then referencing the ith variable through something like ``loc v `v' `:word `i' of `r(varlist)''`` or ``loc v=word("`r(varlist)'",`i')``. – Aspen Chen Sep 26 '14 at 21:50

2 Answers2

3

I can imagine several ways:

  1. Some code like

    sysuse auto, clear
    
    quietly ds
    local myvar `:word 5 of `r(varlist)''
    
    display "`myvar'"
    
    <do something with local myvar>
    

    will get you a way of working with the fifth variable without knowing its name. You can use loops and define list of variables in this way. This is basically a response from http://www.stata.com/statalist/archive/2010-03/msg00073.html.

  2. Convert your database to a matrix and work with that. See help svmat and help matrix.

  3. Use a Mata function like st_varname(). See help Mata and help mf_st_varname. See also help m4_stata.

But I haven't encountered situations in which this is a natural way to proceed.

Roberto Ferrer
  • 11,024
  • 1
  • 21
  • 23
2

Here's two ways of doing it (without renaming variables and with):

sysuse auto, clear

/* Without Renaming Variables */
unab varlist: _all
local K: word count `varlist'

forvalues v=1/`K' {
    local v`v': word `v' of `varlist'
    di "v`v' is `v`v''"
}


matrix dissim ED1 = `v2' `v12', L2 variables
matrix list ED1


/* Rename Variables */
rename * v#, renumber
matrix dissim ED2 = v2 v12, L2 variables
matrix list ED1
dimitriy
  • 9,077
  • 2
  • 25
  • 50