├── Base_Certification_Resource_Guide.md ├── Import_all_files_one_type ├── LICENSE ├── PROC%20MEANS%20Tutorial.slides.html ├── README.md ├── Reporting Example.sas ├── SAS - Graphs in SAS.pptx ├── SAS UE - How to work with big files.md ├── SAS_export_multiple_workbook_worksheet.sas ├── Turning a program into a macro.md ├── _config.yml ├── add_average_value_to_dataset.sas ├── copy_rename_files.sas ├── count_distinct_by_group.sas ├── create_base_data_for_text_analysis.sas ├── create_running_total_by_group.sas ├── proc_format_example.sas ├── proc_means_basic.sas ├── sas_macro_loop_ods_excel ├── select_top_records.sas ├── sgplot_control_path_type ├── sgplot_intro_example ├── sgplot_line_graph_animation └── text_analysis.sas /Base_Certification_Resource_Guide.md: -------------------------------------------------------------------------------- 1 | # SAS - Recommended References for learning specific topics 2 | 3 | The initial purpose of this was to create a free or almost free reference guide to study towards SAS certification. 4 | I fully believe the SAS Certification Prep Guide is quite good at covering the SAS material, but sometimes you need some more background or more information. 5 | 6 | 7 | Each topic will be listed as a heading and links to the reference documents will be underneath. 8 | I'm currently adding resources that may or may not be related to the Base SAS certification but that are still really good and useful to know. 9 | 10 | **_This is a work in progress that will be completed over time. If you have suggestions feel free to drop me a line at stat_geek hotmail.com_** 11 | 12 | ## Create temporary and permanent SAS data sets. 13 | Still looking for a reference! 14 | 15 | ## Combine SAS Data Sets 16 | **_This one is a big issue and is such an important part of working iwth data that I'll separate this into a few different sections._** 17 | 18 | ### Concatenate Data Sets 19 | https://support.sas.com/resources/papers/proceedings/pdfs/sgf2008/085-2008.pdf 20 | 21 | ### Merge Data Sets: one-to-one 22 | 23 | #### SQL 24 | https://support.sas.com/resources/papers/proceedings/proceedings/forum2007/109-2007.pdf 25 | _This covers SQL in significant detail and not all items are relevant to joins/unions though it's useful to know._ 26 | 27 | #### Data Step 28 | _In this case, the best reference I've come across is the documentation. The order isn't great, but it still goes over everything you need to know. I recommend reading this entire chapter._ 29 | https://documentation.sas.com/?docsetId=lrcon&docsetTarget=n1xc1y8c37apw7n1erbitmuiwvds.htm&docsetVersion=9.4&locale=en 30 | 31 | ## Investigate SAS data libraries using base SAS utility procedures. 32 | 33 | http://support.sas.com/resources/papers/proceedings11/274-2011.pdf 34 | 35 | ## Access an Excel workbook. 36 | 37 | https://video.sas.com/detail/video/3862987502001/import-a-microsoft-excel-spreadsheet?autoStart=true&q=import%20excel 38 | 39 | ## Create and manipulate SAS date values 40 | https://communities.sas.com/t5/SAS-Communities-Library/Working-with-Dates-and-Times-in-SAS-Tutorial/ta-p/424354?attachment-id=13253 41 | 42 | ## Export data to create standard and comma-delimited raw data files. 43 | 44 | https://stats.idre.ucla.edu/sas/faq/how-do-i-write-out-a-file-that-uses-commas-tabs-or-spaces-as-delimiters-to-separate-variables-in-sas/ 45 | 46 | ## Control which observations and variables in a SAS data set are processed and output. 47 | 48 | Drop, Keep, & Where (note OUTPUT statement is not covered in this section). 49 | https://newonlinecourses.science.psu.edu/stat481/node/13/ 50 | 51 | 52 | ## Lead and Lags - understanding queues in SAS 53 | This is a good reference on how to use LEAD/LAG and the gotcha's involved in working with these functions. 54 | https://support.sas.com/resources/papers/proceedings16/11221-2016.pdf 55 | 56 | 57 | # Macro Language References 58 | 59 | ## UCLA introductory tutorial on macro variables and macros 60 | https://stats.idre.ucla.edu/sas/seminars/sas-macros-introduction/ 61 | 62 | ## Tutorial on converting a working program to a macro 63 | This method is pretty robust and helps prevent errors and makes it much easier to debug your code. 64 | Obviously biased, because I wrote it :) 65 | https://github.com/statgeek/SAS-Tutorials/blob/master/Turning%20a%20program%20into%20a%20macro.md 66 | 67 | ## Examples of common macro usage 68 | https://communities.sas.com/t5/SAS-Communities-Library/SAS-9-4-Macro-Language-Reference-Has-a-New-Appendix/ta-p/291716 69 | 70 | -------------------------------------------------------------------------------- /Import_all_files_one_type: -------------------------------------------------------------------------------- 1 | 2 | %*Creates a list of all files in the DIR directory with the specified extension (EXT); 3 | %macro list_files(dir,ext); 4 | %local filrf rc did memcnt name i; 5 | %let rc=%sysfunc(filename(filrf,&dir)); 6 | %let did=%sysfunc(dopen(&filrf)); 7 | 8 | %if &did eq 0 %then 9 | %do; 10 | %put Directory &dir cannot be open or does not exist; 11 | 12 | %return; 13 | %end; 14 | 15 | %do i = 1 %to %sysfunc(dnum(&did)); 16 | %let name=%qsysfunc(dread(&did,&i)); 17 | 18 | %if %qupcase(%qscan(&name,-1,.)) = %upcase(&ext) %then 19 | %do; 20 | %put &dir\&name; 21 | %let file_name = %qscan(&name,1,.); 22 | %put &file_name; 23 | 24 | data _tmp; 25 | length dir $512 name $100; 26 | dir=symget("dir"); 27 | name=symget("name"); 28 | path = catx('\',dir,name); 29 | the_name = substr(name,1,find(name,'.')-1); 30 | run; 31 | 32 | proc append base=list data=_tmp force; 33 | run; 34 | 35 | quit; 36 | 37 | proc sql; 38 | drop table _tmp; 39 | quit; 40 | 41 | %end; 42 | %else %if %qscan(&name,2,.) = %then 43 | %do; 44 | %list_files(&dir\&name,&ext) 45 | %end; 46 | %end; 47 | 48 | %let rc=%sysfunc(dclose(&did)); 49 | %let rc=%sysfunc(filename(filrf)); 50 | %mend list_files; 51 | 52 | %*Macro to import a single file, using the path, filename and an output dataset name must be specified; 53 | %macro import_file(path, file_name, dataset_name ); 54 | 55 | proc import 56 | datafile="&path.\&file_name." 57 | dbms=xlsx 58 | out=&dataset_name replace; 59 | run; 60 | 61 | %mend; 62 | 63 | *Create the list of files, in this case all XLSX files; 64 | %list_files(c:\_localData\temp, xlsx); 65 | 66 | %*Call macro once for each entry in the list table created from the %list_files() macro; 67 | data _null_; 68 | set list; 69 | string = catt('%import_file(', dir, ', ', name,', ', catt('test', put(_n_, z2.)), ');'); 70 | call execute (string); 71 | run; 72 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | SAS tutorials 2 | ========== 3 | 4 | This is where I'll be storing different code tidbits that can be used as examples or references for myself or other users. 5 | 6 | -------------------------------------------------------------------------------- /Reporting Example.sas: -------------------------------------------------------------------------------- 1 | *Example of generating automated reports via Macro Loop with names mapped for unique file name mapping; 2 | *create example data; 3 | 4 | data cars; 5 | set sashelp.cars; 6 | run; 7 | 8 | proc sort data=sashelp.cars out=cars; 9 | by make; 10 | run; 11 | 12 | *add sequence numbers to mimic your structure; 13 | 14 | data cars; 15 | set cars; 16 | by make; 17 | retain SeqNo; 18 | 19 | if first.make then 20 | seqNo + 1; 21 | run; 22 | 23 | *get max of seq for loop; 24 | 25 | proc sql noprint; 26 | select max(seqNo) into :NumObs from cars; 27 | quit; 28 | 29 | *create format to map numbers to make; 30 | 31 | proc sql; 32 | create table mapSeq2Make as select distinct seqNo as Start, trim(Make) as 33 | Label, 'make_fmt' as fmtName, 'N' as type from cars; 34 | quit; 35 | 36 | *create format; 37 | 38 | proc format cntlin=mapSeq2Make; 39 | run; 40 | 41 | *test mapping; 42 | %put %sysfunc(putn(1, make_fmt)); 43 | *macro to create reports; 44 | 45 | %macro report_make(); 46 | %do i=1 %to &numObs; 47 | ods html file="/home/fkhurshed/Demo1/MileageReport_%sysfunc(putn(&i, make_fmt)).html" /*1*/ 48 | gpath='/home/fkhurshed/Demo1/' style=meadow; 49 | ods graphics / imagemap=on; 50 | title "Report on Mileage for %sysfunc(putn(&i, make_fmt))"; 51 | 52 | /*2*/ 53 | title2 'Summary Statistics'; 54 | 55 | proc means data=sashelp.cars (where=(make="%sysfunc(putn(&i, make_fmt))")) 56 | /*3*/ 57 | N Mean Median P5 P95 MAXDEC=2; 58 | class type; 59 | ways 0 1; 60 | var mpg_city mpg_highway; 61 | run; 62 | 63 | title 'City vs Highway Mileage'; 64 | 65 | proc sgplot data=sashelp.cars (where=(make="%sysfunc(putn(&i, make_fmt))")) 66 | /*4*/; 67 | scatter x=mpg_city y=mpg_highway / group=type; 68 | run; 69 | 70 | ods html close; 71 | %end; 72 | %mend report_make; 73 | 74 | *execute macro; 75 | %report_make(); 76 | -------------------------------------------------------------------------------- /SAS - Graphs in SAS.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/statgeek/SAS-Tutorials/a5e9348b917853b12e91744be51dcde0144b8c1b/SAS - Graphs in SAS.pptx -------------------------------------------------------------------------------- /SAS UE - How to work with big files.md: -------------------------------------------------------------------------------- 1 | # SAS UE - Working with Big Files 2 | 3 | ## Set up the VM 4 | *No specific instructions on how to do this, because it changes between tools and versions* 5 | 1. Shut down the VM 6 | 2. Set the # of cores to 2 - this is the limit in SAS UE 7 | 3. Set the RAM to as much as you can - remember this is using your computer's RAM so everything else will be slower, especially if you leave the VM rumming 8 | 4. Set up another shared folder, either under myfolders or to a location you will remember 9 | 5. Start/Restart VM 10 | 11 | 12 | ## Set up a user library 13 | 14 | One way to make things faster is to redirect the WORK library. You can do this by creating a user library. The downside to this approach, is you need to remember to remove the files. SAS will keep the files there between sessions until you explicitly delete them. 15 | 16 | libname user '/folders/myshortcuts/path to folder from step 4 above; 17 | 18 | 19 | -------------------------------------------------------------------------------- /SAS_export_multiple_workbook_worksheet.sas: -------------------------------------------------------------------------------- 1 | /*This program is designed to show how you can automate the creation of workbooks in Excel. 2 | The criteria is to create a workbook for every Origin value in the CARS data set and 3 | in each workbook, create a separate sheet for each make. 4 | For example, it will create a workbook for Asia, with sheets for all the makes include Kia, Honda, Hyundai, etc. 5 | 6 | Author: F.Khurshed 7 | Date: 2018-04-05 8 | */ 9 | 10 | 11 | %*Generate sample data to work with here; 12 | proc sort data=sashelp.cars out=cars; 13 | by origin make; 14 | run; 15 | 16 | *Close other destinations to improve speed; 17 | ods listing close; 18 | ods html close; 19 | 20 | *macro that exports to file with Origin in file name and a 21 | sheet for each make. The number of origins or makes is not 22 | needed ahead of time; 23 | 24 | %macro export_origin(origin=); 25 | 26 | %*filename for export, set style for fun and add label for each sheet; 27 | ods excel file="C:\_localdata\Cars_&origin..xlsx" 28 | style = meadow 29 | options(sheet_interval='bygroup' 30 | sheet_label='Make'); 31 | 32 | *generate a sheet for each make (by make); 33 | proc print data=cars noobs label; 34 | where origin = "&Origin"; 35 | by make; 36 | run; 37 | 38 | %*close excel file; 39 | ods excel close; 40 | 41 | %mend; 42 | 43 | *calls macro for each origin in file. 44 | number of origins doesn't need to be known ahead of time; 45 | 46 | data _null_; 47 | set cars; 48 | by origin; 49 | 50 | if first.origin then do; 51 | *create macro call; 52 | str = catt('%export_origin(origin=', origin, ');'); 53 | *call macro; 54 | call execute(str); 55 | 56 | end; 57 | 58 | run; 59 | 60 | %*reopens output destinations; 61 | ods html; 62 | ods listing; 63 | -------------------------------------------------------------------------------- /Turning a program into a macro.md: -------------------------------------------------------------------------------- 1 | 2 | # Tutorial - Turning a program into a macro 3 | 4 | One of the most asked question on the forum is how to create or convert a piece of code into a macro. Usually the correct answer is not to use a macro and I avoid them as much as possible myself. BY group processing is incredibly powerful and you can usually manipulate the data to avoid mulitple processing. Why do I avoid macro's? Because every read of the data and creating output takes up processing power and takes more time. Macro's typically loop so you are doing a lot of processing. For small data sets usually used in classrooms or while learning, you won't see any significant difference, but as soon as your data starts getting bigger this is more important. Especially if you aren't working on a server. 5 | 6 | This tutorial is not for beginners, you should have some base programming knowledge already. In fact, this is based on the concept that you have a working piece of code first. 7 | 8 | ## Problem 9 | 10 | PHB has requested you create a report for each Make of car in the SASHELP.CARS data set. The report should include: 11 | 12 | 1. Average values for mileage, city and highway, by vehicle type (TYPE) via PROC MEANS 13 | 2. A scatter plot of MPG_Highway vs MPG_City with the type identified in the plot 14 | 3. A title indicating the model covered in the report 15 | 4. The files should be named CARS_MAKE, eg CARS_Toyota, CARS_Mercedes 16 | 17 | Fortunately for you, you already have a report because PHB asked for this a week ago for Toyota's but now you need to change it to run for all models. 18 | 19 | The program is shown below: 20 | 21 | 22 | ``` 23 | ods html file = "/folders/myfolders/MileageReport_Toyota.html" 24 | gpath= '/folders/myfolders/' 25 | style = meadow; 26 | 27 | ods graphics / imagemap=on ; 28 | title 'Report on Mileage for Toyota'; 29 | title2 'Summary Statistics'; 30 | proc means data=sashelp.cars (where=(make='Toyota')) N Mean Median P5 P95 MAXDEC=2; 31 | class type; 32 | ways 0 1; 33 | var mpg_city mpg_highway; 34 | run; 35 | 36 | title 'City vs Highway Mileage'; 37 | proc sgplot data=sashelp.cars (where=(make='Toyota')); 38 | scatter x=mpg_city y=mpg_highway / group = type; 39 | run; 40 | ``` 41 | 42 | # Step 1 43 | The next step is to find identify all locations where we ues the MAKE and need to change it. Examining the code we can find 4 places where the Make is used. Each section of the code where MAKE is found is indicated with a number. 44 | 1. ODS HTML Statement - used to control file name 45 | 2. TITLE statement - used to display the title in the report 46 | 3. PROC MEANS WHERE data set option - filters the data for PROC MEANS 47 | 4. PROC SGPLOT WHERE data set option - filters the data for PROC SGPLOT 48 | 49 | 50 | ```sas 51 | ods html file = "/folders/myfolders/MileageReport_Toyota.html" /*1*/ 52 | gpath= '/folders/myfolders/' 53 | style = meadow; 54 | 55 | ods graphics / imagemap=on ; 56 | title 'Report on Mileage for Toyota'; /*2*/ 57 | title2 'Summary Statistics'; 58 | proc means data=sashelp.cars (where=(make='Toyota')) /*3*/ N Mean Median P5 P95 MAXDEC=2; 59 | class type; 60 | ways 0 1; 61 | var mpg_city mpg_highway; 62 | run; 63 | 64 | title 'City vs Highway Mileage'; 65 | proc sgplot data=sashelp.cars (where=(make='Toyota')) /*4*/; 66 | scatter x=mpg_city y=mpg_highway / group = type; 67 | run; 68 | 69 | ods html close; 70 | 71 | ``` 72 | 73 | # Step 2 - Macro Variables 74 | 75 | We start by creating a macro variable and replacing all instances of make, with the macro variable. 76 | In addition, we need to switch all quotation marks from single to double quotes. Macro variables do not resolve in single quotes. 77 | 78 | To create a macro variable you use %LET macroVariableName = 79 | 80 | 81 | ```sas 82 | %let r_make=Toyota; 83 | 84 | ods html file = "/folders/myfolders/MileageReport_&r_make..html" /*1*/ 85 | gpath= '/folders/myfolders/' 86 | style = meadow; 87 | 88 | ods graphics / imagemap=on ; 89 | title "Report on Mileage for &r_make."; /*2*/ 90 | title2 'Summary Statistics'; 91 | proc means data=sashelp.cars (where=(make="&r_make.")) /*3*/ N Mean Median P5 P95 MAXDEC=2; 92 | class type; 93 | ways 0 1; 94 | var mpg_city mpg_highway; 95 | run; 96 | 97 | title 'City vs Highway Mileage'; 98 | proc sgplot data=sashelp.cars (where=(make="&r_make.")) /*4*/; 99 | scatter x=mpg_city y=mpg_highway / group = type; 100 | run; 101 | 102 | ods html close; 103 | ``` 104 | 105 | # Step 3 - Convert to a macro 106 | 107 | The next step is to convert this to a macro by sandwiching the code between %macro and %mend. 108 | 109 | A key thing is to test it after each step. Note the macro call at the end of the program. 110 | 111 | 112 | ```sas 113 | 114 | %let r_make=Toyota; 115 | 116 | %macro report_make; 117 | ods html file = "/folders/myfolders/MileageReport_&r_make..html" /*1*/ 118 | gpath= '/folders/myfolders/' 119 | style = meadow; 120 | 121 | ods graphics / imagemap=on ; 122 | title "Report on Mileage for &r_make."; /*2*/ 123 | title2 'Summary Statistics'; 124 | proc means data=sashelp.cars (where=(make="&r_make.")) /*3*/ N Mean Median P5 P95 MAXDEC=2; 125 | class type; 126 | ways 0 1; 127 | var mpg_city mpg_highway; 128 | run; 129 | 130 | title 'City vs Highway Mileage'; 131 | proc sgplot data=sashelp.cars (where=(make="&r_make.")) /*4*/; 132 | scatter x=mpg_city y=mpg_highway / group = type; 133 | run; 134 | 135 | ods html close; 136 | 137 | %mend report_make; 138 | 139 | %report_make; 140 | 141 | ``` 142 | 143 | # Step 4 - Add parameters 144 | 145 | In this step, we remove the %LET statement that created the macro variables previously and we replace it with a parameter in the %MACRO statement. 146 | 147 | 148 | ```sas 149 | %macro report_make(r_make=); 150 | ods html file = "/folders/myfolders/MileageReport_&r_make..html" /*1*/ 151 | gpath= '/folders/myfolders/' 152 | style = meadow; 153 | 154 | ods graphics / imagemap=on ; 155 | title "Report on Mileage for &r_make."; /*2*/ 156 | title2 'Summary Statistics'; 157 | proc means data=sashelp.cars (where=(make="&r_make.")) /*3*/ N Mean Median P5 P95 MAXDEC=2; 158 | class type; 159 | ways 0 1; 160 | var mpg_city mpg_highway; 161 | run; 162 | 163 | title 'City vs Highway Mileage'; 164 | proc sgplot data=sashelp.cars (where=(make="&r_make.")) /*4*/; 165 | scatter x=mpg_city y=mpg_highway / group = type; 166 | run; 167 | 168 | ods html close; 169 | 170 | %mend report_make; 171 | 172 | *execute macro; 173 | %report_make(r_make = Toyota); 174 | ``` 175 | 176 | # Step 5 - Get list of all makes 177 | 178 | The macro is now available so the final step is to run all reports. Because this is a demo I limit it to 5 runs. The first step is to get a list of all makes. 179 | 180 | 181 | ```sas 182 | *get list of all makes; 183 | proc sql; 184 | create table car_makes as 185 | select distinct make 186 | from sashelp.cars; 187 | quit; 188 | 189 | ``` 190 | 191 | # Step 6 - Run macro for all makes in list 192 | 193 | To do this, I prefer CALL EXECUTE. For CALL EXECUTE, it will run the command passed to it. So I create a string that looks like my macro call, pass it to CALL EXECUTE, which runs the program. 194 | 195 | 1. Make a string that looks like: 196 | %report_make(r_make = [insert make variable]); 197 | 2. Pass the string to CALL EXECUTE. 198 | 199 | Other options: 200 | * Macro list of makes and a macro loop 201 | * DOSUBL 202 | * Manual list of macros via copy/paste 203 | 204 | 205 | ```sas 206 | data macro_call; 207 | set car_makes (obs=5); *run only 5 for testing; 208 | 209 | *build macro call string; 210 | str = catt('%report_make(r_make =', make, ');'); 211 | 212 | *call macro; 213 | call execute(str); 214 | 215 | run; 216 | ``` 217 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /add_average_value_to_dataset.sas: -------------------------------------------------------------------------------- 1 | 2 | ******************************************************; 3 | *Add average value to a dataset; 4 | *Solution 1 - PROC MEANS + Data step; 5 | ******************************************************; 6 | 7 | proc means data=sashelp.class noprint; 8 | output out=avg_values mean(height)=avg_height; 9 | run; 10 | 11 | data class_data; 12 | set sashelp.class; 13 | 14 | if _n_=1 then 15 | set avg_values; 16 | run; 17 | 18 | proc print data=class; 19 | run; 20 | 21 | *Solution 2 - PROC SQL - note the warning in the log; 22 | PROC SQL; 23 | Create table class_sql as 24 | select *, mean(height) as avg_height 25 | from sashelp.class; 26 | quit; 27 | 28 | ******************************************************; 29 | *Add average value to a dataset - with grouping variables; 30 | *Solution 1 - PROC MEANS + Data step; 31 | ******************************************************; 32 | proc means data=sashelp.class noprint nway; 33 | class sex; 34 | output out=avg_values mean(height)=avg_height; 35 | run; 36 | 37 | *sort data before merge; 38 | proc sort data=sashelp.class out=class; 39 | by sex; 40 | run; 41 | 42 | data class_data; 43 | merge class avg_values; 44 | by sex; 45 | 46 | 47 | run; 48 | 49 | proc print data=class_data; 50 | run; 51 | 52 | *Solution 2 - PROC SQL - note the warning in the log; 53 | PROC SQL; 54 | Create table class_sql as 55 | select *, mean(height) as avg_height 56 | from sashelp.class 57 | group by sex; 58 | quit; 59 | -------------------------------------------------------------------------------- /copy_rename_files.sas: -------------------------------------------------------------------------------- 1 | 2 | /*This is an example of how to copy and rename files in a data step*/ 3 | 4 | %list_files(&path, csv); 5 | 6 | options msglevel=i; 7 | 8 | data renameProcess; 9 | set list; 10 | 11 | *process to rename; 12 | status_ref1 = filename('fr1', path); 13 | 14 | *build filename with dates; 15 | path2 = catt(dir, "/Sample/", name, "_", put(today(), yymmddn8.), ".csv"); 16 | status_ref2 = filename('fr2', path2); 17 | 18 | *process to copy; 19 | status_copy = fcopy('fr1', 'fr2'); 20 | 21 | if status_copy=0 then 22 | put 'Copied SRC to DEST.'; 23 | else do; 24 | msg=sysmsg(); 25 | put status_copy= msg=; 26 | end; 27 | 28 | run; 29 | -------------------------------------------------------------------------------- /count_distinct_by_group.sas: -------------------------------------------------------------------------------- 1 | /*This demonstrates how to count the number of unique occurences of a variable 2 | across groups. It uses the SASHELP.CARS dataset which is available with any SAS installation. 3 | The objective is to determine the number of unique car makers by origin/ 4 | 5 | Note: The SQL solution can be off if you have a large data set and these are not the only two ways to calculate distinct counts. 6 | If you're dealing with a large data set other methods may be appropriate.*/ 7 | 8 | *Count distinct IDs; 9 | proc sql; 10 | create table distinct_sql as 11 | select origin, count(distinct make) as n_make 12 | from sashelp.cars 13 | group by origin; 14 | quit; 15 | 16 | *Double PROC FREQ; 17 | proc freq data=sashelp.cars noprint; 18 | table origin * make / out=origin_make; 19 | run; 20 | 21 | proc freq data=origin_make noprint; 22 | table origin / out= distinct_freq; 23 | run; 24 | 25 | title 'PROC FREQ'; 26 | proc print data=distinct_freq; 27 | run; 28 | title 'PROC SQL'; 29 | proc print data=distinct_sql; 30 | run; 31 | -------------------------------------------------------------------------------- /create_base_data_for_text_analysis.sas: -------------------------------------------------------------------------------- 1 | *Set up library to store project files; 2 | libname ta '/folders/myshortcuts/program/TextAnalysis/SAS Files'; 3 | *Specify the path to the parts of speech file; 4 | filename corpus 5 | '/folders/myshortcuts/program/TextAnalysis/Corpus/sample_sas_forum.txt'; 6 | *Specify the path to the sentiment word file; 7 | filename sent 8 | '/folders/myshortcuts/program/TextAnalysis/Corpus/word_sentiment.txt'; 9 | 10 | 11 | *Import parts of speech file; 12 | data ta.corpus; 13 | informat text $100. word $100. pos $8.; 14 | infile corpus dlm='D7'x termstr=CR truncover; 15 | input text $; 16 | word=scan (text, 1, '◊'); 17 | pos=scan(text, 2, '◊'); 18 | pos_length = length(pos); 19 | 20 | array _pos(7) $1 pos1-pos7; 21 | 22 | do i=1 to pos_length; 23 | _pos(i)=char(pos, i); 24 | end; 25 | 26 | drop i text; 27 | 28 | run; 29 | 30 | *Close file connection; 31 | filename corpus; 32 | 33 | *Import sentiment file; 34 | data ta.sentiment; 35 | informat word $50.; 36 | infile sent dsd dlm=',' truncover firstobs=2; 37 | input word $ happiness_rank happiness_average happiness_standard_deviation twitter_rank google_rank nyt_rank lyrics_rank; 38 | run; 39 | 40 | *close file connection; 41 | filename sent; 42 | 43 | *Create the pos lookup table; 44 | proc format; 45 | invalue $ pos_infmt 46 | 'N' = 'Noun' 47 | 'p' = 'Plural' 48 | 'h' = 'Noun Phrase' 49 | 'V' = 'Verb (usu participle)' 50 | 't' = 'Verb (transitive)' 51 | 'i' = 'Verb (intransitive)' 52 | 'A' = 'Adjective' 53 | 'v' = 'Adverb' 54 | 'C' = 'Conjunction' 55 | 'P' = 'Preposition' 56 | '!' = 'Interjection' 57 | 'r' = 'Pronoun' 58 | 'D' = 'Definite Article' 59 | 'I' = 'Indefinite Article' 60 | 'o' = 'Nominative' 61 | ; 62 | value $ pos_fmt 63 | 'N' = 'Noun' 64 | 'p' = 'Plural' 65 | 'h' = 'Noun Phrase' 66 | 'V' = 'Verb (usu participle)' 67 | 't' = 'Verb (transitive)' 68 | 'i' = 'Verb (intransitive)' 69 | 'A' = 'Adjective' 70 | 'v' = 'Adverb' 71 | 'C' = 'Conjunction' 72 | 'P' = 'Preposition' 73 | '!' = 'Interjection' 74 | 'r' = 'Pronoun' 75 | 'D' = 'Definite Article' 76 | 'I' = 'Indefinite Article' 77 | 'o' = 'Nominative' 78 | ; 79 | run; 80 | -------------------------------------------------------------------------------- /create_running_total_by_group.sas: -------------------------------------------------------------------------------- 1 | *generate sample data; 2 | data baseball; 3 | set sashelp.baseball; 4 | keep team name salary; 5 | run; 6 | 7 | *sort on Grouping variable, for BY statement; 8 | proc sort data=baseball; 9 | by team name; 10 | run; 11 | 12 | *add totals; 13 | data want; 14 | set baseball; 15 | by team name; *same as from PROC SORT; 16 | retain total_salary; *keeps values across rows; 17 | 18 | if first.team then total_salary = sum(0, salary); *reset for first record; 19 | else total_salary = sum(total_salary, salary); *accumulate; 20 | run; 21 | -------------------------------------------------------------------------------- /proc_format_example.sas: -------------------------------------------------------------------------------- 1 | /*this is an example of creating a custom format and then applying it to a data set*/ 2 | 3 | *create the format; 4 | proc format; 5 | value age_group 6 | low - 13 = 'Pre-Teen' 7 | 13 - 15 = 'Teen' 8 | 16 - high = 'Adult'; 9 | run; 10 | 11 | title 'Example of an applied format'; 12 | proc print data=sashelp.class; 13 | format age age_group.; *applies the format; 14 | run; 15 | 16 | 17 | data class; 18 | set sashelp.class; 19 | age_category = put(age, age_group.); *creates a character variable with the age category; 20 | label age_category = 'Age Category'; *adds a nice label for the printed output; 21 | run; 22 | 23 | title 'Example of creating a new variable with the format'; 24 | proc print data=class label; 25 | run; 26 | 27 | *show format used directly; 28 | 29 | proc freq data=sashelp.class; 30 | table age / out= formatted_age; 31 | format age age_group.; 32 | run; 33 | 34 | -------------------------------------------------------------------------------- /proc_means_basic.sas: -------------------------------------------------------------------------------- 1 | *Create summary statistics for a dataset by a 'grouping' variable and store it in a dataset; 2 | 3 | *Generate sample fake data; 4 | data have; 5 | input ID feature1 feature2 feature3; 6 | cards; 7 | 1 7.72 5.43 4.35 8 | 1 5.54 2.25 8.22 9 | 1 4.43 6.75 2.22 10 | 1 3.22 3.21 7.31 11 | 2 6.72 2.86 6.11 12 | 2 5.89 4.25 5.25 13 | 2 3.43 7.30 8.21 14 | 2 1.22 3.55 6.55 15 | 16 | ; 17 | run; 18 | 19 | *Create summary data; 20 | proc means data=have noprint; 21 | by id; 22 | var feature1-feature3; 23 | output out=want median= var= mean= /autoname; 24 | run; 25 | 26 | *Show for display; 27 | proc print data=want; 28 | run; 29 | 30 | *First done here:https://communities.sas.com/t5/General-SAS-Programming/Getting-creating-new-summary-variables-longitudinal-data/m-p/347940/highlight/false#M44842; 31 | *Another way to present data is as follows; 32 | 33 | proc means data=have stackods nway n min max mean median std p5 p95; 34 | by id; 35 | var feature1-feature3; 36 | ods output summary=want2; 37 | run; 38 | 39 | *Show for display; 40 | proc print data=want2; 41 | run; 42 | -------------------------------------------------------------------------------- /sas_macro_loop_ods_excel: -------------------------------------------------------------------------------- 1 | /*This code generates a new tab for each age in the workbook*/ 2 | proc sql noprint; 3 | select distinct age into : age1- 4 | from sashelp.class; 5 | quit; 6 | 7 | %let num_ages = &sqlobs.; 8 | 9 | %macro loop; 10 | ods excel file='C:\_localdata\temp\test.xlsx'; 11 | %do i=1 %to &num_ages; 12 | %put &i; 13 | 14 | ods excel options (sheet_name="Age = &&age&i"); 15 | 16 | proc print data=sashelp.class; 17 | where age=&&age&i; 18 | run; 19 | 20 | %end; 21 | %mend; 22 | 23 | ods excel close; 24 | 25 | %loop; 26 | -------------------------------------------------------------------------------- /select_top_records.sas: -------------------------------------------------------------------------------- 1 | /* A commonly asked question is how to get the top X by each group 2 | or the bottom Y for each group. In general, one method is to create 3 | a counter variable that increments and you can then filter based on the 4 | counter. This method does not account for ties, however. If you need to get tied 5 | observations, you need a different approach. An example would be if there were 6 | multiple records for each day for the stocks. 7 | To get the top X or bottom N, remember that you can reverse your sort 8 | (ascending/default to descending) to use the same methodology 9 | 10 | Author: F.Khurshed 11 | Date: 2018-02-24 12 | */ 13 | 14 | %*sort; 15 | proc sort data=sashelp.stocks out=stocks; 16 | by stock descending date; 17 | run; 18 | 19 | data want; 20 | set stocks; 21 | %*set grouping by stock; 22 | by stock; 23 | %* 24 | if first of a group set counter to 1; 25 | 26 | if first.stock then 27 | counter=1; 28 | %*increment counter; 29 | else 30 | counter+1; 31 | %*keep only records that are less than 5, ie first 5 records; 32 | 33 | if counter <=5; 34 | run; 35 | -------------------------------------------------------------------------------- /sgplot_control_path_type: -------------------------------------------------------------------------------- 1 | *specify the path to where the files should be saved; 2 | ods listing gpath='/folders/myfolders/'; 3 | *specify the output type; 4 | ods graphics / imagename='mygraph' imagefmt=png; 5 | proc sgplot data=sashelp.class; 6 | scatter x=weight y=height; 7 | run;quit; 8 | 9 | 10 | *Demo for creating a PDF; 11 | ods pdf file='/folders/myfolders/demo.pdf' style=meadows; 12 | 13 | proc sgplot data=sashelp.class; 14 | scatter x=weight y=height; 15 | run;quit; 16 | 17 | ods pdf close; 18 | -------------------------------------------------------------------------------- /sgplot_intro_example: -------------------------------------------------------------------------------- 1 | proc sort data=sashelp.iris out=iris; 2 | by species; 3 | run; 4 | 5 | /*SGScatter sample*/ 6 | proc sgscatter data=iris; 7 | By Species; 8 | matrix petallength petalwidth sepallength / ellipse=(type=mean) 9 | diagonal=(histogram kernel); 10 | run; 11 | 12 | /*Bar Chart*/ 13 | data bar_chart; 14 | input question answer $ value; 15 | cards; 16 | 1 Yes 98 17 | 1 No 2 18 | ; 19 | run; 20 | 21 | proc sgplot data=bar_chart; 22 | hbar answer / response=value stat=SUM; 23 | label answer='Response' value='Percent'; 24 | run; 25 | 26 | quit; 27 | 28 | *Change to stacked bar chart; 29 | proc sgplot data=bar_chart; 30 | hbar question / group=answer response=value stat=SUM groupdisplay=stack 31 | CATEGORYORDER=RESPDESC; 32 | label answer='Response' value='Percent'; 33 | xaxis min=96; 34 | yaxis display=none; 35 | run; 36 | 37 | quit; 38 | 39 | *Customize the axis - within procedure changes, add title; 40 | proc sgplot data=bar_chart; 41 | hbar question / group=answer response=value stat=SUM groupdisplay=stack 42 | CATEGORYORDER=RESPDESC; 43 | label answer='Response' value='Percent'; 44 | xaxis min=96; 45 | yaxis display=none; 46 | title 'Does truncating an axis lead to misleading interpretations'; 47 | run; 48 | 49 | 50 | *Switch graph types: 51 | hbar to vbar 52 | switch y vs x axis statements; 53 | proc sgplot data=bar_chart; 54 | vbar question / group=answer response=value stat=SUM groupdisplay=stack 55 | CATEGORYORDER=RESPDESC; 56 | label answer='Response' value='Percent'; 57 | yaxis min=96; 58 | xaxis display=none; 59 | title 'Does truncating an axis lead to misleading interpretations'; 60 | run; 61 | 62 | *Broken axis instead?; 63 | proc sgplot data=bar_chart; 64 | vbar question / group=answer response=value stat=SUM groupdisplay=stack 65 | CATEGORYORDER=RESPDESC; 66 | label answer='Response' value='Percent'; 67 | yaxis ranges=(0-10 90-100); 68 | 69 | /*specify the ranges for broken range*/ 70 | xaxis display=none; 71 | title 'Broken Axis instead?'; 72 | run; 73 | 74 | 75 | 76 | 77 | *Line Graph; 78 | proc sgplot data=sashelp.stocks; 79 | where stock = 'IBM'; 80 | series x=date y= open; 81 | run;quit; 82 | -------------------------------------------------------------------------------- /sgplot_line_graph_animation: -------------------------------------------------------------------------------- 1 | /*--This program requires SAS 9.4--*/ 2 | %macro lineAnnually(dsn=, start=, end=); 3 | %let start=%sysfunc(inputn(&start,anydtdte9.)); 4 | %let end=%sysfunc(inputn(&end,anydtdte9.)); 5 | %let dif=%sysfunc(intck(month,&start,&end)); 6 | %do i=0 %to &dif; 7 | %let date=%sysfunc(intnx(month,&start,&i,b),date9.); 8 | 9 | proc sgplot data=sashelp.stocks; 10 | where date > &start and date < "&date"d and stock='IBM'; 11 | series x=date y=open; 12 | xaxis interval=month min='01Jan1990'd max='01Jan2007'd; 13 | yaxis values=(0 to 200 by 50); 14 | footnote j=l 'Created using the SGPLOT Procedure, using SAS UE'; 15 | run; 16 | 17 | quit; 18 | %end; 19 | %mend lineAnnually; 20 | 21 | 22 | 23 | /*--Create animation--*/ 24 | options papersize=('11 in', '7 in') 25 | printerpath=gif 26 | animation=start 27 | animduration=0.1 28 | animloop=yes 29 | noanimoverlay 30 | nodate; 31 | ods printer file='/folders/myfolders/LineGraph.gif'; 32 | 33 | ods graphics / width=10in height=6in imagefmt=GIF; 34 | 35 | %lineAnnually(dsn=sashelp.stocks , start=01Jan1990, end=01Jan2007); 36 | 37 | options printerpath=gif animation=stop; 38 | ods printer close; 39 | 40 | -------------------------------------------------------------------------------- /text_analysis.sas: -------------------------------------------------------------------------------- 1 | *Create sample data; 2 | data random_sentences; 3 | infile cards truncover; 4 | informat sentence $256.; 5 | input sentence $256.; 6 | cards; 7 | This is a random sentence 8 | This is another random sentence 9 | Happy Birthday 10 | My job sucks. 11 | This is a good idea, not. 12 | This is an awesome idea! 13 | How are you today? 14 | Does this make sense? 15 | Have a great day! 16 | ; 17 | ; 18 | ; 19 | ; 20 | 21 | *Partition into words; 22 | data f1; 23 | set random_sentences; 24 | id=_n_; 25 | nwords=countw(sentence); 26 | nchar=length(compress(sentence)); 27 | 28 | do word_order=1 to nwords; 29 | word=scan(sentence, word_order); 30 | output; 31 | end; 32 | run; 33 | 34 | *Add happiness index and pos; 35 | 36 | proc sql ; 37 | create table scored as 38 | select a.*, b.happiness_rank, c.pos, c.pos1 39 | from f1 as a 40 | left join ta.sentiment as b 41 | on a.word=b.word 42 | left join ta.corpus as c 43 | on a.word=c.word 44 | order by sentence, word_order; 45 | quit; 46 | 47 | *Calculate sentence happiness score; 48 | proc sql; 49 | create table sentence_sentiment as 50 | select distinct sentence, sum(happiness_rank) as sentiment 51 | from scored 52 | group by id; 53 | quit; 54 | --------------------------------------------------------------------------------