Hi all,

I am a newbie to Stata, recently transitioned from R. I am struggling with combining the length and grep commands in R to get a count of variables with a specific stub in every row of my frame. The data looks like below (nearly 300 variables, only simplified here):
ID NP1 NP2_1 NP3_9 GE1 GE2 GE3 GE4 GE5 GE6 NP_length
1 0 0 1 1 0 0 9 9 3
1 2 1 1 1 1 1 4 3 3
2 5 3
2 0 3 4 5 7 8 1 2 3
I need to add the "NP_length" column with the count of variables NP* (here it would be 3). In R I could do it by the following way:
df$np_length<-length(grep(x=colnames(df), pattern="NP"))

Some things I have thought of/tried:
  1. I think egen may help here, but the help page does not provide information on counting variables in a pre-defined varlist and adding it as a variable.
  2. Tried local word count of varlist but it doesn't add the count of variables as a column in the frame
  3. I tried using the below code with a loop to just add the variable with stub NP* count as a new column in my frame. The count in the column "NP_length" is not getting updated beyond 0 for some reason:
    gen NP_length = 0
    local NP_list NP*
    foreach var in `r(NP_list)' {
    replace NP_length = NP_length+1
    }
Can someone help with an elegant solution?