Reputation: 66819
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.
Upvotes: 1
Views: 4684
Reputation: 11102
I can imagine several ways:
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.
Convert your database to a matrix
and work with that. See help svmat
and help matrix
.
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.
Upvotes: 3
Reputation: 9460
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
Upvotes: 2