[英]how to swap first and last observations in sas data set if it contain 3 observations
我有一个包含 3 个观察值的数据集,1 2 3 4 5 6 7 8 9,现在我必须交换 1 2 3 和 7 8 9。如何在基础 sas 中做到这一点?
If you just want to sort your dataset by a variable in descending order, use proc sort:如果您只想按降序按变量对数据集进行排序,请使用 proc sort:
data example;
input number;
datalines;
123
456
789
;
run;
proc sort data = example;
by descending number;
run;
If you want to re-order a dataset in a more complex way, create a new variable containing the position that you want each row to be in, and then sort it by that variable.如果您想以更复杂的方式对数据集重新排序,请创建一个包含您希望每一行所在位置的新变量,然后按该变量对其进行排序。
If you want to swap the contents of the first and last observations while leaving the rest of the dataset in place, you could do something like this.如果你想交换第一个和最后一个观察的内容,同时保留数据集的其余部分,你可以做这样的事情。
data class;
set sashelp.class;
run;
data firstobs;
i = 1;
set sashelp.class(obs = 1);
run;
data lastobs;
i = nobs;
set sashelp.class nobs = nobs point = nobs;
output;
stop;
run;
data transaction;
set lastobs firstobs;
/*Swap the values of i for first and last obs*/
retain _i;
if _n_ = 1 then do;
_i = i;
i = 1;
end;
if _n_ = 2 then i = _i;
drop _i;
run;
data class;
set transaction(keep = i);
modify class point = i;
set transaction;
run;
This modifies just the first and last observations, which should be quite a bit faster than sorting or replacing a large dataset.这只会修改第一个和最后一个观察结果,这应该比排序或替换大型数据集快得多。 You can do a similar thing with the update statement, but that only works if your dataset is already sorted / indexed by a unique key.您可以使用 update 语句执行类似的操作,但仅当您的数据集已按唯一键排序/索引时才有效。
By Sandeep Sharma:sandeep.sharmas091@gmail.com
data testy;
input a;
datalines;
1
2
3
4
5
6
7
8
9
;
run;
data ghj;
drop y;
do i=nobs-2 to nobs;
set testy point=i nobs=nobs;
output;
end;
do n=4 to nobs-3;
set testy point=n;
output;
end;
do y=1 to 3;
set testy;
output;
end;
stop;
run;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.