Change All Value Labels to Numerics in SPSS - label

I need to change all the value labels of all my variables in my spss file to be the value itself.
I first tried -
Value Labels ALL.
EXECUTE.
This removes the value labels, but also removes the value entirely. I need this to have a label of some sort as I am converting the file and when there is no values defined it turns the value into a numeric. Therefore, I need the all value labels changed into numbers so that each value's label is just the value - value = 1 then label = 1.
Any ideas to do this across all my variables??
Thanks in advance!!

Here is a solution to get you started:
get file="C:\Program Files\IBM\SPSS\Statistics\23\Samples\English\Employee data.sav".
begin program.
import spss, spssaux, spssdata
spss.Submit("set mprint on.")
vd=spssaux.VariableDict(variableType ="numeric")
for v in vd:
allvalues = list(set(item[0] for item in spssdata.Spssdata(v.VariableName, names=False).fetchall()))
if allvalues:
cmd="value labels " + v.VariableName + "\n".join([" %(i)s '%(i)s'" %locals() for i in allvalues if i <> None]) + "."
spss.Submit(cmd)
spss.Submit("set mprint off.")
end program.
You may want to read this to understand the behaviour of fetchall in reading date variables (or simply exclude date variables from having their values labelled also, if they cause no problems?)

Related

how to use while loop in pseudocode

I am trying to add the user inputs using a while loop and If statements. I am having trouble figuring out how to add all the userNumbers to each other. Any help would be appreciated.
//variables
Declare Integer userIn = 0
Declare Integer total = 0
//read numbers and calculate
While decision == decY
Display “Please enter your numbers: ”
Input decision
If UserIn > 0
Display userNumbers
Set total = userIn + 1
Display “Would you like to enter another number Y/N?”
Input decision
If decision == decN
Display “Done reading numbers, your total is ”, total
End If
End If
End While
Decide on a separator for the input, unless they're only allowed to enter a single number at a time in which case you can skip to 3.
Use string splitting to cut the input up and then loop through that list with for, while, do, until, or etc.
Create a sum total variable and add each input value to it, e.g. sum = sum + split_input[index], or if it will only allow a single input at a time sum = sum + input.
Some Notes:
Adding a value to a variable can be shortened to variable += value to add a value to an existing variable and assign the result to the variable, but not all languages support this syntax.
Not all programming languages start at 0 for list indices, so be sure to change the starting index accordingly.

AddField function does not work as expected

I have the following block of code that iterates through the fields of each table and adds the fields of the current table respectively in order to create a number of tableboxes.
'iterate through every table
For i=1 To arrTCount
'the arrFF array holds the names of the fields of each table
arrFF = Split(arrFields(i), ", ")
arrFFCount = UBound(arrFF)
'create a tablebox
Set TB = ActiveDocument.Sheets("Main").CreateTableBox
'iterate through the fields of the array
For j=0 to (arrFFCount - 1)
'add the field to the tablebox
TB.AddField arrFF(j)
'Msgbox(arrFF(j))
Next
Set tboxprop = TB.GetProperties
tboxprop.Layout.Frame.ObjectId = "TB" + CStr(i)
TB.SetProperties tboxprop
Next
The above code creates the tableboxes, but with one field less every time (the last one is missing). If I change the For loop from For j=0 To (arrFFCount - 1) to For j=0 To (arrFFCount) it creates empty tableboxes and seems to execute forever. Regarding this change, I tested the field names with the Msgbox(arrFF(j)) command and it shows me the correct field names as I want them to be in the tableboxes in the UI of QlikView.
Does anybody have an idea of what seems to be the problem here? Can I do this in a different way?
To clarify the situation here and what I have tested so far, I have 11 tables to make tableboxes of and I have tried with just one of them or some of them. The result I am seeing with the code is on the left and what I am expecting to see is on the right of the following image. Please note that the number of fields vary for each table and the image has just one of them as an example.

Get Capped Maximum Value From List

I have a list of values that range anywhere from 500-1000. I have a second list of values that denote relevant breakpoints in the 500-1000 range (500, 520, 540, 600, etc). I need to return the highest value in the second list that is less than the value in a given number from the first list. I noticed the "N" functions let you set a conditional on them, so for example if I do:
List.Max(List.FirstN(SomeTable[Breakpoints], each _ < 530))
It correctly returns 520 to me. However if I put this inside an AddColumn function and change the 530 to a local field reference:
Table.AddColumn(MyTable, "MinValue", each List.Max(List.FirstN(SomeTable[Breakpoints], each _ < [SomeNumbers])))
Then I get a "We cannot apply field access to the type Number" error. Is what I'm trying to do possible and I'm just formatting it wrong? I always get confused with scope and references in PQ, so it may just be that.
After each, [SomeNumbers] by itself is short for _[SomeNumbers] (which is what you see when filtering a column). In the List.FirstN call, _ refers to a number in the list instead of a row in a table: the value of _ is tied to the closest each, where closeness is measured by the number of layers of nesting between _ and the appearance of each . Therefore, in your code [SomeNumbers] is trying to find the column SomeNumbers on a number, which doesn't exist.
There are a couple ways to fix this:
You can use a let...in statement to store the current value of the SomeNumbers column to use it for later, like so:
each
let
currentNumber = [SomeNumbers],
result = List.Max(List.FirstN(SomeTable[Breakpoints], each _ < currentNumber))
in
result
You can explicitly define a function with the (x) => ... syntax instead of using each twice, like so:
each List.Max(List.FirstN(SomeTable[Breakpoints], (point) => point < [SomeNumbers]))

What makes Crystal ignore record selection formula?

Crystal 2008. Have record selection formula ending with
and
( ( "Zero" in {?Credit_Debit} and {V_ARHB_BKT_AGING_DETAIL.AMOUNT} = 0)
or ( "Credit" in {?Credit_Debit} and {V_ARHB_BKT_AGING_DETAIL.AMOUNT} < 0)
or ( "Debit" in {?Credit_Debit} and {V_ARHB_BKT_AGING_DETAIL.AMOUNT} > 0) )
but no matter what combination of values is selected for Credit_Debit the result set is the same.
Also without success, I tried joining the parameter array into a single string and using lines like
or ( {#Cred_Deb_Choices} like "*Credit*" and {V_ARHB_BKT_AGING_DETAIL.AMOUNT} < 0)
Using the first method works in the same formula when the parameter values are integers, as:
and ({?Location ID} = 0 or {V_ARHB_BKT_AGING_DETAIL.LOC_ID} in {?Location ID})
I examined the generated SQL, and saw that the part at the beginning that had no effect was not shown.
I changed a part that tested for a hard-coded value to instead test for a parameter value, and looked at the SQL again. No change.
When you try to create a filter that doesn't fit with the datatype of the field then that doesn't get reflected in record selection formula.
For Integer field give integers in record selection for text give text.
E.g:
ID=0 and Name='XXX' works
ID='Zero' and Name='XXX' doesn't
This should solve your issue

What is the pythonic way to print values right aligned?

I've a list of strings which I want to group by their suffix and then print the values right-aligned, padding the left side with spaces.
What is the pythonic way to do that?
My current code is:
def find_pos(needle, haystack):
for i, v in enumerate(haystack):
if str(needle).endswith(v):
return i
return -1
# Show only Error and Warning things
search_terms = "Error", "Warning"
errors_list = filter(lambda item: str(item).endswith(search_terms), dir(__builtins__))
# alphabetical sort
errors_list.sort()
# Sort the list so Errors come before Warnings
errors_list.sort(lambda x, y: find_pos(x, search_terms) - find_pos(y, search_terms))
# Format for right-aligning the string
size = str(len(max(errors_list, key=len)))
fmt = "{:>" + size + "s}"
for item in errors_list:
print fmt.format(item)
An alternative I had in mind was:
size = len(max(errors_list, key=len))
for item in errors_list:
print str.rjust(item, size)
I'm still learning Python, so other suggestions about improving the code is welcome too.
Very close.
fmt = "{:>{size}s}"
for item in errors_list:
print fmt.format(item, size=size)
The two sorting steps can be combined into one:
errors_list.sort(key=lambda x: (x, find_pos(x, search_terms)))
Generally, using the key parameter is preferred over using cmp. Documentation on sorting
If you are interested in the length anyway, using the key parameter to max() is a bit pointless. I'd go for
width = max(map(len, errors_list))
Since the length does not change inside the loop, I'd prepare the format string only once:
right_align = ">{}".format(width)
Inside the loop, you can now do with the free format() function (i.e. not the str method, but the built-in function):
for item in errors_list:
print format(item, right_align)
str.rjust(item, size) is usually and preferrably written as item.rjust(size).
You might want to look here, which describes how to right-justify using str.rjust and using print formatting.

Resources