SAS learning_6:使用proc sql進行數據集管理

深夜有感,寫些小記,告誡自己平復內心。
感覺自己到了人生的關鍵轉折點。爲了將來的生活,我在幾個月前做出了抉擇,但代價是讓最親密的人做出了讓步與犧牲。不善經營感情的我,在學業與愧疚的夾縫中愈發焦慮。
砥礪前行。堅信未來會更美好吧!小耗嘰,加油!

本篇主要記錄自己在學習SAS的過程中,利用proc sql進行數據集管理的常用語句;主要包括proc sql基本語法,變量操作,創建數據集,數據集拼接。若有不正確以及更好的方法,歡迎各位在評論中指出/討論。大家一起學習,共同進步。

1. proc sql語法基本格式:

proc sql;/*define sql procedure */
	select var, count(distinct var) as class_var/*get the number of categories of variable "var", and save it as "class_var"*/
	from mydata.dataset/*dataframe where variable "var" comes from*/
	where physics > 85/*filter obs whose value of "physics" beyond 85*/
	group by sex/*the same as "by" in sas code*/
	having total_score > 680 /*the other filter statement that execuates in each group of var that has been defined in "group by" statement*/
	order by id;/*the same as sort procedure in sas code*/
quit;/*procedure ends*/

2. 創建數據集:

proc sql;
	create table <df-name><as select * from known-df/ like known-df>;
quit;

3. 創建變量分組:

proc sql;
	select *, var1, 
		case when condition then statement1 
		else statement2
		end as var2
		from df;
quit;

例如,可以根據以上case when… else 語句生成新的分類變量,如將連續BMI變量劃分爲4分類變量。

4. 數據集連接:

1) 縱向連接:

差(except): select * from dataset1 except select * from dataset2; 連接dataset1中有而dataset2中沒有的觀測
並(union): select * from dataset1 union select * from dataset2;縱向連接數據集dataset1和dataset2;
交(intersect) 將上述語句 except 改爲intersect即可,連接兩個數據集中相同的觀測
外並(outer union)數據集結構不一致時,使用。也保留所有觀測。

2)橫向連接(join):

左拼接(left join)
select a., b. from dataset1 as a left join dataset2 as b on a.var1=b.var1; 將dataset1作爲a, dataset2作爲b,以共同變量var1進行左連接(保留dataset1的全部觀測);
右拼接(right join)
將左連接中left 改爲right, 保留dataset2的全部觀測;
內連接(inner join)
將左連接中left 改爲inner, 保留匹配的全部觀測;
或:select a., b. from dataset1 as a, dataset2 as b where a.var1=b.var1;
全連接(full join)
將左連接的語法中left 改爲 full即可, 保留兩個數據集的全部觀測(包括非匹配觀測)

後面沒有把語法寫完整,改天有時間再補齊吧~
明天還要早起去雲南的大山搬磚。晚安

最近在看macro的相關內容,下次有機會將結合自己的應用簡單分享下
Micheal

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章