bill999
bill999

Reputation: 2550

How to replace a variable based on a local and subtraction

In one line, I would like to perform an operation on a specific row, the row of which is referenced by a number created by a local subtracting a number.

Here is a MWE:

sysuse auto2, clear
*save the number of observations in a local (is there a quicker way to do this?)
count
local N = r(N)
*make sure it works
di `N'
*make sure that the subtraction works
di `N'-1
*make the replacement, which works when referencing row with `N'
replace make = "def" in `N'
*here is the problem - subtracting from `N' doesn't work
replace make = "abc" in `N'-1

Error:

'74-1' invalid observation number

How can I solve this problem?

Upvotes: 1

Views: 131

Answers (1)

Nick Cox
Nick Cox

Reputation: 37338

There are at least two ways to do this.

  1. Create another local macro:
local Nm1 = `N' - 1 
replace make = "abc" in `Nm1'
  1. Force evaluation of an expression on the fly:
replace make = "abc" in `=`N'-1' 

Upvotes: 1

Related Questions