0

I want to rename variable names starting with intensity. I received an invalid syntax, r(198) error, with the following code.

#delimit;

foreach VAR of varlist intensity* {;

 local NEW = subinstr("`VAR'", "intensity", "int");
 rename `VAR' `NEW';

 };
Nick Cox
  • 35,529
  • 6
  • 31
  • 47
Victor Wang
  • 765
  • 12
  • 26
  • 1
    Not worth a separate answer on its own, but note that using the `trace` feature is (often) a helpful command for debugging. See `help trace`. – Brendan Jul 03 '19 at 12:31

1 Answers1

2

Your use of the delimiter ; here does not bite, so I will ignore it.

The error is in the use of subinstr(), which must have four arguments, the fourth being the number of substitutions to be made. See help subinstr().

This works (note please the use of a minimal complete verifiable example):

clear 
set obs 1 
generate intensity1 = 1 
generate intensity2 = 2 

foreach VAR of varlist intensity* {
    local NEW = subinstr("`VAR'", "intensity", "int", 1)
    rename `VAR' `NEW'
}

ds

But the loop is utterly unnecessary. First, let's flip the names back and then show how to change names directly:

rename int* intensity*
rename intensity* int*

See help rename groups for more.

Nick Cox
  • 35,529
  • 6
  • 31
  • 47