I had more than the two tips on becoming a better programmer than I gave in the last post but I had run out of margarita. Now, being replenished with tequila and fresh lime by The Invisible Developer, here are two more. He often tells me that I should refer to myself as a developer and not a programmer because that is beneath me. I have never pretended to be cool. I started with punched cards as a programmer and a programmer I will remain. At least until the second margarita.

margarita
It’s Friday!

If you aren’t familiar with github, you could have gone to Chris Hemedinger’s super demo at SAS Global Forum. We use github for version control and it is indispensable for that. When you have several people working on the same program, I can edit files, you can, too, and we all upload and download the latest versions without copying over each other’s code. If you are on a project with more than one developer, once you have used a git repository, you’ll fight anyone who tries to take it away.

Because it is so good for sharing, github is used a lot for open source projects and for people just making their code publicly available.

The main thing I learned that I didn’t know is that there is a https://github.com/sassoftware

I had just assumed since SAS is a private company and definitely not open source that there would not be much available. I was wrong.

Whatever language you use, there is probably a github for it.

Here is a funny thing. When I first started learning JavaScript, I scavenged github to find examples of people making simple games like tic-tac-toe , Memory or mazes. I’d modify the code to do what I wanted and I thought all of these people were so much smarter than me.

After I learned a bit more, sometimes I saw functions or libraries in the code that didn’t do anything and I realized that a lot of these people had done the exact same thing as me – copied someone else’s code and modified it for their purposes.

Start by copying code from github, but don’t stop there

If you ask me – and even if you don’t, I’m going to tell you anyway – it is absolutely fine to download code from someone else’s repository on github and tweak it a little for your own purposes. However, don’t stop there! Dive into it. Figure out what each function does, try to understand their logic.

A better person than me would have their own public git repository. Oh well, I have a bucket of private ones for work and I’ve been writing this blog for 11 years, so that will have to do. YOU should definitely have public repository, though. Changing the subject here …

Git Repositories that are NOT python, R or Viya

The top repositories almost all entail either integrating SAS and Python (not surprising because it is open source) or Viya or Visual Analytics (presumably because it is expensive and SAS wants to promote it). There are also a smattering of SAS-and-R repositories in the top hits and repositories for SAS and iOS and SAS and Android. I’m not interested in any of that at the moment.

Right now, I am super-swamped but I should have some free time over the summer, so here are my personal interests I am marking for later. With 116 repositories, any SAS aficionado should find something of interest, and remember, this is just the sassoftware repository. There are additional repositories of individual users, like the last one I noted below

SAS Studio Tasks is an area I’d like to learn more about, as in writing your own custom tasks.

Data mining is an area I am ALWAYS wanting to brush up on more . This library of flow diagrams for specific data mining topics looks really cool.

Not a SAS Institute repository, this one from Michael Friendly is on macros and looks super cool.

As I mentioned above, I started using github for JavaScript code and there are TONS of repositories for just about any language that would tickle your fancy (what exactly IS a fancy, anyway?)

I have more tips but it will have to wait for another margarita and since my grandchildren are spending the weekend and just invaded my office, that will have to wait.

I did a random sample of presentations at SAS Global Forum today, if random is defined as of interest to me, which let’s be honest, is pretty damn random most of the time. 

Tip #1 Stalk Interesting People

I don’t mean in a creepy showing up at their hotel room way. If you see someone presenting either in person or referenced in twitter, blogs, etc. , check out what else that person has freely available on the web, in published proceedings, etc.

Let me give you an example that applies even if you are not into logistic regression. (You’re not? Feel shame.)

The first session I attended was a Super Demo in the exhibit hall which for some reason I don’t understand is always called the Quad. 

In a nutshell, logistic regression is usually 

  • binary, which is where I started out, modeling mortality studies, you’re either dead or alive
  • multinomial, that is, multiple categories, like college major or religion or 
  • ordinal , like someone is a subscriber, contributor, editor or administrator on a group blog, which are progressively higher levels of involvement

What if the data fit the proportional odds model for some of the explanatory variables and not others? You can do a partial proportional odds model. 

Line plots on slide
Graphing your data is a great way to see if the proportional odds model makes sense. You can see that it does for the variable on the right, but for the left, not so much.

Unfortunately, the super demos do not have a paper published in the app or proceedings, however, the presenter, Bob Derr from SAS mentioned he had presented a paper on this topic in 2013 (way to play hard to get, Bob – not!)

Paper reference on slide (also below in blog)

I skipped the next presentation to read it (and to write this post). If you are at all interested in multinomial and ordinal logistic regression, you should, too. You can find it here in the SAS Global Forum 2103 proceedings. http://support.sas.com/resources/papers/proceedings13/446-2013.pdf

It’s an outstanding paper and I am going to require it for my course next year. I think the students will find it far more accessible than some of the readings we have been using. They don’t complain loudly, but I know, I know. 

Tip #2 Read the Documentation (No, seriously, keep reading)

People who answer comments with LMGTFY (let me Google that for you) or RTFM (read the fucking manual), just so you know, that quit being funny around 1990. However, SAS documentation really is a treasure trove. It’s not just SAS, the same could be said about jQuery documentation or the WordPress Codex but we’re not talking about those today, are we? Please try to stay on topic. 

The SAS documentation runs many, many thousands of pages. It’s far better and more detailed than you would think. Let me give you an example a very helpful person named Michael pointed out in the Quad (what the hell is it with that name?) today. As I’ve mentioned several times lately, my students often struggle with repeated measures ANOVA. He suggested checking out the page on longitudinal data analysis.

http://support.sas.com/rnd/app/stat/procedures/LongitudinalAnalysis.html

It gives four different procedures (none of which are GLM, I noted, but that’s a discussion for another day). 

Related to that, I recommend when you are learning procedures just running some of the code examples. For example, here is one for repeated measures with PROC MIXED. http://documentation.sas.com/?docsetId=statug&docsetTarget=statug_mixed_examples02.htm&docsetVersion=15.1&locale=en. (Yes, I really do have that on my mind lately)

Think about this, though. Once you graduate from whatever your last degree turns out to be, you don’t have anyone checking your work and telling you if it is right or not. You just write your code and hope for the best. That sucks, huh?

When you are learning a new procedure, you can write code using the data shown in the SAS documentation and see if your results match. Like an answer key for life! I always wanted one of those.

Since the last few posts detailed errors in repeated measures with PROC GLM , I thought I should acknowledge that people seem to struggle just as much with PROC MIXED.

Forgetting data needs to be multiple rows

This is one of the first points of confusion for students. When you do a PROC MIXED, you need multiple records for each person. So, thinking back to my previous example with three time points, with PROC MIXED, and two options for treatment, my dataset needs to look like this:

SubjectExamTreatmentScore
1PreTalk43
1PostTalk46
1FollowTalk45
2PreDrug39

With GLM, you’d have 3 variables, named Pre, Post and Follow, for example (you *did* read the last post, right?). In PROC MIXED, your dataset has to be structured so that you have one variable, in this case, named “exam”, and it takes on one of three possible values.

Let’s start with the simplest case. I’d like to know, just like before, if there was a change from pre to post-test and if it was maintained at follow-up. In other words, my question is, “Was there a difference between the pretest and post-test and a difference between pretest and follow-up six months later?” I am not particularly interested in the post-test/ followup difference as such. Here is one way to code it:

Proc mixed data = example ;
class subject exam;
model score = exam ;
random subject ;
contrast “pre vs post” exam 1 -1 0 ;
contrast “pre vs follow” exam 1 0 -1 ;


The PROC GLM code from this post will give you the exact same results as the code above, but only if you have your data structured so that you have three variables instead of three records for each person.

I have a lot to say about CONTRAST statements, which I love, and random effects, about which I am neutral, and nested effects, that are not relevant to this example but could be. However, I am trying to not work past 9 pm and it’s already an hour later so … until next time.

Also, if you’re at SAS Global Forum, be sure to meet up and say “Hey!”

This is my day job …

Check it out. I make games that teach math, including, of course, statistics. Play AzTech: Meet the Maya – the only statistics game with Honduran fruit bats.

As I said in my last post, repeated measures ANOVA seems to be one of the procedures that confuses students the most. Let’s go through two ways to do an analysis correctly and the most common mistakes.

Our first example has people given an exam three times, a pretest, a posttest and a follow up and we want to see if the pretest differs from the other two time points.

proc glm data = example ;
model pre post follow = /nouni ;
repeated exams 3 contrast (1) /summary printm ;

Among other things, this will give you a table of Type III Sum of Squares that tells you that you have a significant difference across time. It will also give you contrasts between the 1st treatment and each of the other two.

You can see all of the output produced here.

This is using PROC GLM and so it requires that you have multiple VARIABLES representing each of the multiple times you measured people. This is in contrast to PROC MIXED which requires multiple records for each subject. We’ll get into that another day.

One thing that throws people all of the time is they ask, “Where did you get the exams variable?” In fact, I could have used any valid SAS name. It could have been “Nancy” instead of “exams” and that would have worked just as well. It’s a label we use for the factor measured multiple times. So, as counterintuitive as it sounds, there is NO variable named “exams” in your data set.

Let’s try a different example. This time, I have a treatment variable. I have administered two different treatments to my subjects. I want to see if treatment has any effect on improvement.

proc glm data =example ;
class treatment ;
model pre post follow = treatment/ nouni ;
repeated exams 3 /summary ;

The fixed effect does *not* go in your REPEATED statement

In this case, I do need a CLASS statement to specify my fixed effect of treatment. A really common mistake that students make is to code the REPEATED statement like this:

repeated treatment 3 /summary ; *WRONG! ;

It seems logical, right? Why would you use a completely made up name instead of one of your variables? If you think about it for a minute, though, treatment wasn’t repeated. Each subject only received one type of treatment.

When you are asking whether one group improved more than the other(s) what you are asking is, “Is there an interaction effect?” You can see by the table of Type III Sums of Squares produced below that there was no interaction effect.


A significant effect for the repeated measure does not mean your treatment worked!

A common mistake is to look at the significance for the repeated measure and because a significant change was found between times 1 and 3 to say that the treatment had an effect. In fact, though, we can see by the non-significant interaction effect that there was not an impact of treatment because there was no difference in the change in exam scores across the levels of treatment.

There are a lot of other common mistakes but I need to go back to work so those will have to wait for another blog.

When I teach students how to use SAS to do a repeated measures Analysis of Variance, it almost seems like those crazy foreign language majors I knew in college who were learning Portuguese and Italian at the same time.

I teach how to do a repeated measures ANOVA using both PROC GLM and PROC MIXED. It seems very likely in their careers my students will run into both general linear models and mixed models. The problem is that they confuse the two and the result is buggy code.

Let’s start with mistakes in PROC GLM today. Next time we can discuss mistakes in PROC MIXED.

Let’s say I have the simplest possible analysis – I’ve given the same students a pre- and a post-test and want to see if there has been a significant increase from time one to time two.

This will work just fine:

proc glm data =mydata.fl_pre_post ;
model pretest posttest = /nouni ;
repeated time 2 ;

Coding the repeated statement like this will also work

repeated time 2 (1 2) ;

So will

repeated time ;

It almost seems as if anything or nothing after the variable name will work. That’s not true. First of all,

repeated time 2 (a b) ; IS WRONG

… and will give you an error – Syntax error, expecting one of the following: a numeric constant, a datetime constant.

“Levels gives the number of levels associated with the factor being defined. When there is only one within-subject factor, the number of levels is equal to the number of dependent variables. In this case, levels is optional. When more than one within-subject factor is defined, however, levels is required,”

SAS 9.2 Users Guide

So, this explains why you can be happily using your repeated statement without bothering to specify the number of levels for a factor and then one day it doesn’t work. WHY? Because now you have two within-subject factors and you need to specify the number of levels but you don’t know that. This is why, when teaching I always include the number of levels. It will never cause your program to fail, even if it is unnecessary sometimes.

One more cool thing about the repeated statement for PROC GLM, you can do a planned contrast super easy. Let’s say I have done 3 tests, a pretest, a post-test and a follow-up. I want to compare the posttest and followup to the pretest.

proc glm data =mydata.fl_tests ;
model pretest posttest follow = /nouni ;
repeated test_time 3 contrast (1) /summary ;

What this will do is compare each of the other time points to the first one. A common mistake students make is to use a CONTRAST statement here with test_time. This will NOT work, although it will work with PROC MIXED, but that is a story for another day.

I cannot believe that it’s been over two months since I’ve written a post. That is the longest I’ve gone in the ten years I have been writing this blog. I read somewhere that the average blog has the lifespan of a fruit fly – after 31 days most people give it up.

That seems to lead to a cottage industry in taking over dormant sites. This site isn’t exactly stagnant even when I am not blogging because people use it for reference.

I started getting emails about “a somewhat embarrassing page”. At first I was aghast that hackers had redirected clients to a porn site.

Fortunately, no, it was just a failed re-direct attempt that ended up breaking a link so you get a 404 page that literally says, “Well, this is somewhat embarrassing.”

The Invisible Developer spent a good bit of time while we were in New York deleting malware from the site. At first, I was feeling very guilty because I thought my cavalier attitude toward security issues with PHP was the reason, but we did clean up most of the problems pointed out in those comments years ago, so that wasn’t the culprit. I should admit here that Paul and Clint were right and I was wrong. Although we have no data of particular value to anyone on this site, hackers are interested in re-directing sites to get links and for other nefarious purposes.

As near as we can tell it was a plugin on another site that was hosted by us that had not been updated in years. We had several more or less abandoned domains of content we had created for clients over the years. They paid us, we created the content for their course or other purpose, and then just left it up. Kind of like all of that stuff you have in your closets that you just shove to the back because you have room.

That’s all cleaned up now. The site, not the closets. Those are still chaos. For all I know, there is an entire new civilization developing in that closet under the stairs. Or maybe Harry Potter lives there.

As for me, I have been teaching two courses during the past 3 months, where I usually only teach one in a year. After landing back in the U.S. in February, I have been criss-crossing the country. Since the beginning of the year, I think I’ve been in 11 cities, 3 states and 2 countries but I may have forgotten a few.

We also released two new games, Fish Lake Adventure , for the iPad, and a new version of AzTech: Meet the Maya, also for the iPad.

Get it in the app store

My lovely daughter, Ronda, headlined this show called Wrestlemania, which is why we were in New York. We have chosen very different careers , my daughters and I. The Perfect Jennifer, or, as she likes to call herself, “the normal one”, is a middle school history teacher, in case you were wondering. The Spoiled One is currently doing a semester abroad in London. She will be back in the U.S. next month and needs a summer internship. Her talents include Instagram, shopping and soccer. If your company doesn’t need any of those skills, she’s also a good writer. Darling Daughter Number One, is 7 Generation Games CEO, she’s also a good writer, having co-authored a New York Times best seller, but she’s not looking for an internship.

So, anyway, I am back, well for a couple of weeks. Next, I head to SAS Global Forum in Texas for a few days to give a couple of presentations on biostatistics and career advice . You’d think my career advice might be to study biostatistics but, maybe not…

Then, I come home for a couple more weeks and am off to a Tech Inclusion conference in Melbourne, Australia. My talk there is going to be, well – different than most – and that’s all I’m going to say about that.

So, now, I’m back to blogging. I have a few things to say about the infinite number of ways people can incorrectly code a repeated measures ANOVA , subdomains and number needed to treat. Between the next game, new website, two conferences and two grant proposals all coming due before June, I’m sure I’ll fit it in there somewhere.

Stop and read this. It may save you whole lot of grief and panic.

Maybe you’ve heard that a stolen iPhone is nothing more than a brick. Perhaps you feel as if your data is safe.

You have a password and it’s not 123456.

You have find my iPhone.

Allow me to burst your bubble by telling you what happened to me and why it could have been WAY worse. Also, turn off Siri right fucking now. If you cannot bear to part with it, turn it off when locked. Go to Settings , then Siri and Search. Turn off answering when locked.

HOW THIEVES ALMOST GOT AWAY WITH EVERYTHING

On Thursday, when I got of the subway I noticed the side of my bag was unzipped. I didn’t see my phone but my credit card and money was still in the pocket so I didn’t think I was robbed. I just figured I’d thrown it in with my computer. When I got home, i emptied my bag and still couldn’t find it. I used find my iPhone and saw it was 7 miles away. So, I put it in lost mode.

Keep this mind, the thieves had my phone for an hour at most before I noticed and locked it.

After I contacted people from my office and made sure I hadn’t left it there,I erased it.

HOW SIRI IS YOUR ENEMY

In the meantime , the thieves had gotten into my yahoo email and my Facebook  page. How did they do that?

Because when you get your phone and you don’t disable this, Siri will answer hi when your phone is locked. Say,

“Siri, what’s my phone number? Siri, what’s my email?”

…. and Siri will tell you.

So, now the thief has your phone, your phone number and your email. TURN OFF SIRI NOW!

I never would have thought the default setup would have such a huge security flaw.

It gets worse.

Now the thief goes to yahoo, enters your email and click “Forgot my password.” They have the reset sent to your phone and then they reset the password .  Guess what? The default is that messages show up on locked iPhones so they get the message and enter a new password. Now, they have your email and your password and your phone.

Next, they go to Facebook and log in using that email. They say that they have lost the password and have the password reset code sent to your iPhone or email they have stolen.

Now the thief has your email, Facebook, phone and phone number.

By this time, it had maybe been a few hours, I had figured out what they were doing ERASED  my iPhone using the Find my iPhone app, deleted the yahoo email from my Facebook and changed the phone number on my yahoo account .

WATCH OUT FOR PHISHING EMAILS CLAIMING TO HAVE YOUR PHONE

This is where disaster really could have happened. So, I’m back in the office on Friday trying to do a million things plus reset my password on everything , handle things that come up every day with two companies in two countries and in one of my company accounts I get a message from “Find my iPhone “ . It looks legit . It says we’ve found your iPhone. It gives the model of iPhone , storage , how would a thief know that ? If you think about it , duh, they have my iPhone . But I’m thinking someone jacking iPhones on the subway certainly doesn’t have the skills to create something  this professional. So, I click on it.  Nothing happens. Thank God for my internet provider that strips out malicious code .

What this was supposed to have done was take me to a page that asked for my Apple ID and password to prove I was me. I might have done it,too. I’m staying with my ISP for life now.

After I switched phones,I got the same message in a text to my new phone number. I can only guess that either a) they were still logged in when I changed it or b) they searched for me on Google.

!!!!! These were not some gifted thieves. There are actually SERVICES that do this for them ! Want to get the Apple ID  and password of a person whose phone you’ve stolen? Send them all of the info you have and they will create the rack email and text messages !

 

EVEN IF YOUR PHONE IS DISABLED,THEY STILL HAVE YOUR SIM CARD

They can (and did) swap that into another phone. When I thought of it two days later,Dennis disabled the account with ATT and he got a message that it was now disabled on a Huawei phone which is not sold in the US but very popular in Chile .

HERE IS WHAT I DID WRONG BEFORE MY PHONE WAS STOLEN

Obviously the Apple default is a huge security flaw. I should have disabled Siri as I never use it and also disabled messages showing on lock mode.

Ironically, I had the yahoo account on my Facebook account thinking it gave me EXTRA security. I hadn’t really used that account in years .

It was possible to reset my yahoo account from a phone, so if someone had my phone they could get access to my email.

HERE IS WHAT I DID RIGHT

I had a second email account that could NOT be reset from a phone. I used that to lock the thief out before they thought of removing it.

When I changed the password and phone associated with my email and Facebook I picked “Log me out of other devices” so if they were logged in somewhere else they couldn’t just change it back.

My phone does not allow purchases so even when someone had my SIM card they could not use it to buy anything. We turned this off with ATT years ago.

None of my bank information is written down anywhere ,  not passwords, accounts,  SSN, nothing . I memorized them. Logins for things like that Software I bought five years ago and the license are written down , or for that stupid forum on blogs. These are not used for anything important .

Any information that might be important is recorded like this:

Password- same as for that computer we used to have in the living room

Had an Internet service provider that stripped out the script on the phishing email and saved me from a huge mistake.

Called ATT to block the number so no one else could use the SIM card

My social media accounts are not connected. Getting into my Facebook doesn’t allow you access to my Instagram, Twitter or anything else. Whenever Facebook asks to connect to anything I say No.

There is very little information in my social media profiles and some of what has been put there automated by Facebook is wrong. So,if anyone was hoping to use the information they got for identity theft they are out of luck .

WHAT SHOULD YOU DO NOW?

At the very least , this second, disable Siri when locked and turn off notifications when locked.

Turn off purchases from your phone.

Turn off resetting your password from a phone .

Disconnect social media accounts form each other so if someone has one account they don’t have all of them.

And for the love of God quit believing that bullshit that stolen iPhone is no more than a brick!

red line

Support my day job!

Wigwams at sunsey

Learn Native American history, math and English all at the same time. You can play it on your iPad, the web or on your phone (if it isn’t stolen).

 

I was going to write more about reading JSON data but that will have to wait because I’m teaching a biostatistics class and I think this will be helpful to them.

What’s a codebook?

If you are using even a moderately complex data set, you will want a code book. At a minimum, it will tell you the name of each variable, the type (character, numeric or date), a label, if it has one and its position in the data set. It will also tell you the number of records and number of variables in a data set. In SAS, you can get all of this by running a PROC CONTENTS. (Also from a PROC DATASETS but we don’t cover that procedure in this class.)

So, for the sashelp.heart data set, for example, you would see:

output from Proc contents

The variable AgeAtDeath is the 12th variable in the data set. It is numeric, with a length of 8 and the label for it is “Age At Death”. Because it is a numeric variable, if you try to use it for any character functions, like finding a substring, you will get an error. (A substring is a subset of a string, so ‘ABC’ is a substring of ‘ABCDE’.)

Similarly, BP_Status is the 15th variable in the data set, it is a character, with a length of 7 and a label of “Blood Pressure Status”. Because it’s a character variable, if you try to do any procedures or functions that expect numeric variables, like find the mean, you will get an error. The label will be used in output, like in the table below.

Frequency distribution of blood pressure status

This is useful because you may have no idea what BP_Status is supposed to mean. HOWEVER, if you use “Blood Pressure Status” in your statements like the example below, you will get an error.

**** WRONG!!!
Proc means data=sashelp.heart ;
Var blood pressure status ;

Seems unfair, but that’s the way it is.

The above statement will assume you want the means for three separate variables named “blood” “pressure” and “status”.

There are no variables in the data set named “blood” or “pressure” so you will get an error. There is a variable named “status”, but it’s something completely different, a variable telling if the subject is alive or dead.

Even if you don’t have a real codebook available, you should at a minimum start any analysis by doing a PROC CONTENTS so you have the correct variable names and types.

What about these errors I was talking about, though? Where will you see them?

LOOK AT YOUR SAS LOG!!

If you are using SAS Studio , it’s the second tab in the middle window, to the right of the tab that says CODE.

Click on that tab and if you have any SYNTAX errors, they will conveniently show up in red.

Also, if you are taking a course and want help from your professor or a classmate, the easiest way for them to help you is if you is to copy and paste your SAS log into an email, or even better, download it and send it as an attachment.

Just because you have no errors in the SAS log doesn’t mean everything is all good, but it’s always the first place you should look.

To get a table of blood pressure status, you may have typed something like

Proc freq data=sashelp.heart ;
Tables status ;

That will run without errors but it will give you a table that gives status as alive or dead, not blood pressure as high, normal or optimal.

PROC CONTENTS is a sort of “codebook light”. A real codebook should also include the mean, minimum, maximum and more for each variable. We’ll talk about that in the next post. Or, who knows, maybe I’ll finally finish talking about reading in JSON data.

Sometimes data changes shape and type over time. In my case, we had a game that was given away free as a demo. We saved the player’s game state – that is, the number of points they had, objects they had earned in the game, etc. as a JSON object. Happy Day! The game became popular. Schools started using it. We came out with a premium version with lots more activities, a bilingual Spanish-English version, a bilingual Lakota- English version. Life is good.

Making Camp Premium on Google Play 

Once schools started using our games, they wanted data on how much students played, how many problems they answered. This is when life started to get complicated. We added more fields to the JSON object to show which activities they had completed and whether they had won.

Data for one person might look like this, or much, much longer.

“{“”points””:””8″”,””first_trade””:””false””,””first_visit””:””true””, “”has_wigwam””:””true””,””inventory””:””6,3,4,14″”,””inventory_position””:””[{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0},{\””left\””:176,\””top\””:4},{\””left\””:-309,\””top\””:-254},{\””left\””:0,\””top\””:0},{\””left\””:619,\””top\””:-45},{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0},{\””left\””:293,\””top\””:-44},{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0},{\””left\””:0,\””top\””:0}]””,””milestone””:””EarnPage””}”

The JSON engine didn’t work (not surprisingly)

I actually didn’t expect it would work because we didn’t actually have a JSON object but rather a JSON object converted to a string and saved in an SQL database. However, if something would only take a minute, I try it first

libname testmcb JSON fileref =reffile ;

Okay, so what now? We have a variable record length, the values we want might be in any column. It must be really difficult to figure out, right? Not really.

This next bit looks complicated but it actually took very little time to code. Before we get into the code, let’s talk about what I needed to do and why. The “why” is that I want to know how much kids played the games. There are three milestones – logging in, getting a wigwam and trading for items. However, some kids just liked playing the mini-games and they played A LOT without pausing to trade in their points. Also, you can’t just look at how many points they have because they may have traded some points for items. Fortunately, all items cost two points, so I need to compute points + (items in inventory/2).

  • First, there were some records that did NOT start with points, they started with “milestone” because we were coding the JSON object one way and then we switched. (Pause to swear under my breath at people here.) So, I need to decide what type of record it was.
  • Second, I want to read in those variables that are milestones in the game play. That is, is this their first time playing, did they get points, did they get a wigwam and did they trade for anything for their wigwam. I need to keep in mind that a variable might be coded 1 or true if the player passed that milestone and 0, false or null if not. (Pause for more swearing.)
  • Third, I want to create Boolean variables that show whether or not a player passed a particular milestone.
  • Fourth, find out the NUMBER of objects in the inventory.
  • Fifth, divide the number in inventory by two and add to the points

This actually took me very little time. Let’s look at it bit by bit (ha ha).

The first line just assigns a file reference for where my text file is located.

FILENAME reffile '/home/annmaria.demars/data_analysis_examples/data2018/exceldata/mc_bilingualtest.txt';

Data mcb_json ;
INFILE reffile DLM="," LRECL = 1337 ;

*** READ IN FILE, VARIABLES ARE SEPARATED (DELIMITED) BY A COMMA. LENGTH OF THE RECORD IS 1,337 ;

INFORMAT first_trade $40. first_visit $40. has_wigwam $40. ;
INPUT  firstcol $ 15-16 @@ ;
IF firstcol = '":' THEN  INPUT @43 points $ first_trade $ first_visit $ has_wigwam $ ;
ELSE INPUT @15 points $ first_trade  first_visit  has_wigwam  ;

***** READ IN THE VARIABLES FOR TRADING, FIRST VISIT AND WIGWAM AS CHARACTER WITH A LENGTH OF 40 ;
****  READ COLUMNS 15-16 AND STAY ON THAT LINE ;
**** IF THE VALUE IN COLUMNS 15-16 = “:  THEN IT HAD MILESTONE AT THE BEGINNING;
***** THE VARIABLES WE WANT START AT COLUMN 43, OTHERWISE, THEY START AT COLUMN 15;
*** THESE ARE SEPARATED BY COMMAS SO WE CAN JUST LIST THE VARIABLE NAMES;
*** NOTE THAT I NEED TO SPECIFY THAT POINTS IS CHARACTER DATA SINCE IT’S NOT IN MY INFORMAT STATEMENT ;

IF INDEX(first_trade,"true") > 0 or index(first_trade,"1") > 0 then traded =0 ;
ELSE IF INDEX(first_trade,"false") or index(first_trade,"0") then traded =1 ;
IF INDEX(first_visit,"false") or index(first_visit,"0") then play_twice = 1 ;
ELSE IF INDEX(first_visit,"true") or index(first_visit,"null") or index(first_visit,"1") then play_twice = 0 ;
IF INDEX(has_wigwam,"true") then wigwam = 1 ;
ELSE IF INDEX(has_wigwam,"null") > 0 or index(has_wigwam,"0") > 0 then wigwam = 0 ;

*** ABOVE I JUST USE A FEW IF THEN STATEMENTS TO CREATE MY NEW VARIABLES ;
**** The INDEX function returns the position in the variable in the first argument where it finds the value in the second argument;
**** If the value isn’t found, it returns a value of 0 ;

This last step isn’t strictly necessary, except that it is. Here I do a cross-tabulation to make sure that all of the variables were assigned correctly and they were.  For example, you can see that if the value of “has_wigwam” was 0 or null the wigwam variable was set to 0. If has_wigwam was equal to “true” the wigwam variable was set to 1.

PROC FREQ ;
TABLES  traded*first_trade first_visit*play_twice wigwam*has_wigwam ;

Screen shot of table of has_wigwam by wigwam values

This would have worked for the whole JSON object except for the commas in the inventory. If you look at just a piece of the data, you can see that after the variables denoting milestones there is a variable that is actually an array, separated by commas.

“first_visit””:””true””, “”has_wigwam””:””true””,””inventory””:””6,3,4,14″”,”

We’ll look at how to handle that in the next post.

When I was young and knew everything, I would frequently see procedures or statistics and think, “When am I ever going to use THAT?” That was my thought when I learned about this new procedure to transpose a data set. (It was new then. Keep in mind, I learned SAS when I was pregnant with my first child. She is now CEO of a an educational game company and the mother of three children. )

PROC TRANSPOSE is super-useful. You might only think it is useful for transforming data for use with PROC GLM to use with PROC MIXED, or you might have no idea what the hell that means and it is still super-useful.

Let me give you today’s example. I’m looking for data to use in a biostatistics class I’m teaching next month. It’s a small data set, with data on eight states included in the Center for Disease Control’s Autism and Developmental Disabilities Monitoring Network.

The data looks like this:

As you can see, each state is a column. I would like to know, for example, what percentage of people with autism also have a physical disability. There is a way to do it by finding the mean across variables but I want to use this data set for a few examples and it would be much easier for me if each of those categories was a variable.

The code is super simple:

PROC TRANSPOSE DATA=mydata.autism OUT=mydata.autism2 NAME=state;
ID eligibility ;

The NAME = option is not required nor is the ID statement but they will make your life easier.  First, let’s take a look at our new data.

Data set with one record for each state

Now, instead of state being a variable, we have one record for each state, the percent with autism diagnosis only is one  variable, percent with emotional disturbance another, and so on. What the NAME = option does is give a name to that new variable which was the name of each column. If you don’t use that option, the first column would be named  _name_  . Now, with these data it would still be pretty obvious that this variable is the state but in some cases it wouldn’t be obvious at all.

The ID statement is really necessary in this case because otherwise each column is going to be named “COL1”, “COL2” etc.  Personally, I found the ID statement here confusing because normally the ID statement I think of as the individual ID for each record, like a social security number or student ID. In this case, the variable name you give in the ID statement is going to be used to name the variables. So, as you can see above, the first column is named Autism(%), the second is named Emotional Disturbance (%) and so on.

So, that’s it. All I need to do to get means, standard deviation, minimum and maximum is :

PROC MEANS DATA =mydata.autism2;

So, that’s it.

By the way, I get this data set and a few others from SAS Curriculum Pathways. Nice source for small data sets to start off a course.


I live in opposite world, where my day job is making games and I teach statistics and write about programming for fun.  You can check out our games here. You’re probably already pretty good with division but you’ll learn about the Lakota language and culture with Making Camp Lakota.  A bilingual (English-Lakota) game that teaches math.

feather

← Previous PageNext Page →