Dear stata-users,
I would like to write a stata matrix (actually a column vector) into a variable. Its number of rows (k) is smaller then number of observations (n) in the data. I also have a sample mark `touse'.
Since svmat does not allow "if `touse'", when I use svmat, stata writes from the first observation and leaves n-k missing at the end.
I have written a small C code (vectovar.c):
#include "stplugin.h"
STDLL stata_call(int argc, char *argv[])
{
int i, j, n, m, nn;
n = SF_row(argv[0]);
m = SF_col(argv[0]);
// allocate memory depending on whether row- or colvector
if(n==1){
nn = m;
} else {
nn = n;
}
double * tmp = (double *) malloc(nn * sizeof(double));
if(n==1){
for(i=0; i<m; i++){
SF_mat_el(argv[0], 1, i+1, &tmp[i]);
}
} else {
for(i=0; i<n; i++){
SF_mat_el(argv[0], i+1, 1, &tmp[i]);
}
}
// store the result in stata variable
i = 0;
for(j=1; j <= SF_nobs(); j++){
if(SF_ifobs(j)){
SF_vstore(1, j, tmp[i]);
i++;
}
}
return 0;
}
and when I call it using
plugin call vectovar `myvarname' if `touse', `mymatrixname'
it does what I need.
I think that using C for this simple task is an overkill. Is there a stata/mata solution.
Thanks,
Oleg
I would like to write a stata matrix (actually a column vector) into a variable. Its number of rows (k) is smaller then number of observations (n) in the data. I also have a sample mark `touse'.
Since svmat does not allow "if `touse'", when I use svmat, stata writes from the first observation and leaves n-k missing at the end.
I have written a small C code (vectovar.c):
#include "stplugin.h"
STDLL stata_call(int argc, char *argv[])
{
int i, j, n, m, nn;
n = SF_row(argv[0]);
m = SF_col(argv[0]);
// allocate memory depending on whether row- or colvector
if(n==1){
nn = m;
} else {
nn = n;
}
double * tmp = (double *) malloc(nn * sizeof(double));
if(n==1){
for(i=0; i<m; i++){
SF_mat_el(argv[0], 1, i+1, &tmp[i]);
}
} else {
for(i=0; i<n; i++){
SF_mat_el(argv[0], i+1, 1, &tmp[i]);
}
}
// store the result in stata variable
i = 0;
for(j=1; j <= SF_nobs(); j++){
if(SF_ifobs(j)){
SF_vstore(1, j, tmp[i]);
i++;
}
}
return 0;
}
and when I call it using
plugin call vectovar `myvarname' if `touse', `mymatrixname'
it does what I need.
I think that using C for this simple task is an overkill. Is there a stata/mata solution.
Thanks,
Oleg
Comment