Searching for individual numbers within a multi-digit response

Mark77

New Member
I have a numeric variable that contains all combinations of 1 through 6 (e.g. 12, 124, 34, 6, 56, etc). I want to create a new dichotomous variable based on whether a certain number is within these combinations of numbers. For example, if I have:
12
134
45
16
I want to be able to create a new dichotomous variable for whether or not response includes the number "1". In this case, responses 12, 134, and 16 would produce the answer 1 whereas 45 would produce a 0. I know I could state "If (varname=12 or varname=13 or varname=123, etc) newvar=1" but I wanted something more elegant given the amount of combinations. Any thoughts?

Last edited:

SiBorg

New Member
Hi Mark

Let's say your starting numeric variable is VAR1.

First, set the decimal places to 0 and then change it to a string variable by simply changing the variable's type on the variable view.

So VAR1 is now a string, not a number. By doing this, you allow SPSS to search for a character (which, in this case is the number "1") within the string (this is not possible to do when it is stored as a number)

Define a second variable, newvar as a numeric variable.

Then run the following.

IF (RINDEX(VAR1,"1")=0) newvar = 0.
EXECUTE.
IF (NOT(RINDEX(VAR1,"1")=0)) newvar=1.
EXECUTE.

RINDEX(haystack,needle) Numeric. Returns an integer that indicates the starting position of the last occurrence of the string needle in the string haystack. Returns 0 if needle does not occur within haystack.
RINDEX will return 0 if "1" isn't found within the string VAR1. The above code therefore uses this result to determine the new dichotomous variable.

BW

Simon

Last edited:

Mark77

New Member
Thank you! Greatly appreciate the swift reply and info!

Hi Mark

Let's say your starting numeric variable is VAR1.

First, set the decimal places to 0 and then change it to a string variable by simply changing the variable's type on the variable view.

So VAR1 is now a string, not a number. By doing this, you allow SPSS to search for a character (which, in this case is the number "1") within the string (this is not possible to do when it is stored as a number)

Define a second variable, newvar as a numeric variable.

Then run the following.

IF (RINDEX(VAR1,"1")=0) newvar = 0.
EXECUTE.
IF (NOT(RINDEX(VAR1,"1")=0)) newvar=1.
EXECUTE.

RINDEX will return 0 if "1" isn't found within the string VAR1. The above code therefore uses this result to determine the new dichotomous variable.

BW

Simon

SiBorg

New Member
No worries. If you found it useful you could do me a big favour by clicking the 'thanks' button!

BW

Simon