Created
November 24, 2018 06:35
-
-
Save statcompute/ab9f4dfc28d8c881a6195988172031f6 to your computer and use it in GitHub Desktop.
Fetch sas data set to lua table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data one; | |
array c{2} $ _temporary_ ("A", "B"); | |
do i = 1 to dim(c); | |
x = c[i]; | |
do j = 1 to 2; | |
y = round(rannor(1), 0.0001); | |
output; | |
end; | |
end; | |
run; | |
proc lua; | |
submit; | |
-- OPEN SAS DATASET FOR READING -- | |
local dsid = sas.open("work.one", i) | |
-- CREATING AN EMPTY LUA TABLE -- | |
local list = {} | |
-- LOOP THROUGH OBSERVATIONS IN SAS DATASET -- | |
for obs in sas.rows(dsid) do | |
local dict = {} | |
-- LOOP THROUGH VARIABLES IN EACH OBSERVATION -- | |
for var in sas.vars(dsid) do | |
dict[var.name] = obs[var.name] | |
end | |
-- INSERT EACH RECORD INTO LUA TABLE -- | |
table.insert(list, dict) | |
-- CLOSE SAS DATASET AFTER THE LAST RECORD -- | |
if #list == sas.nobs(dsid) then | |
sas.close(dsid) | |
end | |
end | |
-- PRINT OUT LUA TABLE -- | |
for i = 1, #list do | |
print(string.rep("*", 5).." RECORD: "..i.." "..string.rep("*", 5)) | |
for key, value in pairs(list[i]) do | |
print(key.." --> "..type(value).." --> "..value) | |
end | |
print("\n") | |
end | |
-- WRITE LUA TABLE INTO NEW SAS DATASET -- | |
new_ds = "work.two" | |
sas.write_ds(list, new_ds) | |
-- SUBMITTING SAS CODE -- | |
sas.submit([[proc print data = @ds@ noobs; run]], {ds = new_ds}) | |
endsubmit; | |
run; | |
*** OUTPUT SHOWN IN THE LOG *** | |
***** RECORD: 1 ***** | |
y --> number --> 1.8048 | |
j --> number --> 1 | |
i --> number --> 1 | |
x --> string --> A | |
***** RECORD: 2 ***** | |
y --> number --> -0.0799 | |
j --> number --> 2 | |
i --> number --> 1 | |
x --> string --> A | |
***** RECORD: 3 ***** | |
y --> number --> 0.3966 | |
j --> number --> 1 | |
i --> number --> 2 | |
x --> string --> B | |
***** RECORD: 4 ***** | |
y --> number --> -1.0833 | |
j --> number --> 2 | |
i --> number --> 2 | |
x --> string --> B |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment