Reputation:
I want to check if a character variable is present in 9 other character variables, but I struggle writing a piece of code that can automatically generate a list of variables for each observation in my dataset. Here's an example of the dataset that I have:
| ID | MainVar | Var1 | Var2 | Var3 | Var4 | Var5 | Var6| Var7 | Var8 | Var9 |
| 1 | Apple | Orange | Pear | | | | | | | |
| 2 | Pear | Apple | Pear | Orange | | | | | | |
I would like to output a flag or something similar for ID 1, which does not have MainVar present in Var1-9. So looking something like this:
| ID | MainVar | Var1 | Var2 | Var3 | Var4 | Var5 | Var6| Var7 | Var8 | Var9 | Err_msg |
| 1 | Apple | Orange | Pear | | | | | | | | Check list |
| 2 | Pear | Apple | Pear | Orange | | | | | | | |
My code looks like this:
Data Want;
set have;
if MainVar not in (Var1, Var2, Var3, Var4, Var5, Var6, Var7, Var8, Var9) then Err_msg = 'Check list';
run;
SAS generated the following error:
ERROR 22-322: Syntax error, expecting one of the following: a quoted string, a numeric constant, a datetime constant,
a missing value, iterator, (.
I assume I need to generate an actual liste of quoted strings, even though all the VAR1-9 variables are indeed character strings. Does anyone have an easy fix for this?
Upvotes: 0
Views: 1730
Reputation: 51566
Just use the WHICHx function. If MAINVAR and VAR1-VAR9 are character use WHICHC() and if they are numeric use WHICHN. This will also allow you to use variable lists.
data want;
set have;
if not whichc(mainvar, of var1-var9) then Err_Msg = 'Check list';
run;
Upvotes: 1
Reputation:
I managed to come up with a solution myself.
Data want;
set have;
array list Var1 Var2 Var3 Var4 Var5 Var6 Var7 Var8 Var9;
if MainVar not in list then Err_Msg = 'Check list';
run;
Seems pretty simple and works quite all right.
Upvotes: 1
Reputation: 7769
On way would be to concatenate all the var
variables into a string, and use index
length allvars $1000. ;
allvars = catx('|', of Var:) ;
if index(allvars,strip(MainVar)) = 0 then ErrMsg = 'Check list' ;
Upvotes: 0