Check if a variable exist

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Check if a variable exist

Alex Huang
CONTENTS DELETED
The author has deleted this message.
Reply | Threaded
Open this post in threaded view
|

Re: Check if a variable exist

Jignesh Sutar
This post was updated on .
It's probably most likely the looping you are trying to do could be better
done all in Python, so no need to have an !VarExist function (which isn't
possible with native syntax anyway). You can use Python sets to deduce
whether variables exist or not, here is a demo to get you started:


get file="C:\Program Files\IBM\SPSS\Statistics\22\Samples\English\Employee
data.sav".

/* ### ### */.
begin program.
import spssaux
spss.Submit("set mprint on.")

myvars= """educ jobcat salary""" # test with all existing vars
myvars= """educ jobcat salary foo poo loo""" # test with non-existing vars
allvars = [x.lower() for x in spssaux.VariableDict(caseless=True).variables]
varsNotExist = set(myvars.split())-set(allvars)
if varsNotExist:
    raise ValueError("The following variables do not exist:\n\n%s" %
("\t\n".join("%s) %s" % (i,j) for i,j in enumerate(varsNotExist,start=1))))
else:
    print "IF (varExist) Bar=1."

spss.Submit("set mprint off.")
end program.
/* ### ### */.


On 2 February 2015 at 02:58, Alex Huang <alexhuangah1@gmail.com> wrote:

> Hello,
>
> I would like to write some syntax in SPSS in the sense if a variable exist,
> a list of operations would be passed to SPSS. I have the following PYTHON
> syntax for this purpose:
>
> BEGIN PROGRAM.
> import spss
> exist = 0
> for i in range(spss.GetVariableCount()):
>     name=spss.GetVariableName(i)
>     if name == "varname":
>         exist = 1
> if not(exist):
>     spss.Submit(["/* Operations here*/"])
>     spss.Submit(["EXECUTE. "])
> END PROGRAM.
>
> I would like to use it for more than 10 times. Is it possible to reduce the
> syntax to simply:
>
> If (!VarExist) /* Operations here...*/.
>
> by defining some macros or others?
>
> (I am new to SPSS macros and also using Python in SPSS syntax.)
>
> Thank you very much in advance.
>
> Cheers,
> Alex
>
>
>
> --
> View this message in context:
> http://spssx-discussion.1045642.n5.nabble.com/Check-if-a-variable-exist-tp5728553.html
> Sent from the SPSSX Discussion mailing list archive at Nabble.com.
>
> =====================
> To manage your subscription to SPSSX-L, send a message to
> LISTSERV@LISTSERV.UGA.EDU (not to SPSSX-L), with no body text except the
> command. To leave the list, send the command
> SIGNOFF SPSSX-L
> For a list of commands to manage subscriptions, send the command
> INFO REFCARD
>

=====================
To manage your subscription to SPSSX-L, send a message to
LISTSERV@LISTSERV.UGA.EDU (not to SPSSX-L), with no body text except the
command. To leave the list, send the command
SIGNOFF SPSSX-L
For a list of commands to manage subscriptions, send the command
INFO REFCARD