Sorting 删除只有一个不同变量的观察值
这可能很容易做到,但我发现在SAS很难做到 我想删除所有变量都相同但只有一个的观测值。我只想保持一个观察而不是两个 范例Sorting 删除只有一个不同变量的观察值,sorting,duplicates,sas,Sorting,Duplicates,Sas,这可能很容易做到,但我发现在SAS很难做到 我想删除所有变量都相同但只有一个的观测值。我只想保持一个观察而不是两个 范例 DATA auto ; INPUT make $ mpg $ rep78 $ weight $ foreign $; CARDS ; AMC 22 3 2930 0 AMC 22 3 2930 1 AMC 22 3 2930 0 AMC 22 3 2930 1 Audi 23 5 2830 1 Audi 23 3 2070 1
DATA auto ;
INPUT make $ mpg $ rep78 $ weight $ foreign $;
CARDS ;
AMC 22 3 2930 0
AMC 22 3 2930 1
AMC 22 3 2930 0
AMC 22 3 2930 1
Audi 23 5 2830 1
Audi 23 3 2070 1
;
RUN ;
在AMC中,我们有3个条目与最后两个匹配,除了在外部中,其中为0和1。现在我只想保留其中一个
示例取自以下网站
对于更新的示例,我需要清理AMC,同时只保留one1和one0。目前它有4个条目
如果您只想保持其中一个相邻,我们可以通过从第二次观察开始的语句将数据集与其自身合并,而不使用。很可能还有其他方法(例如proc-sql),而不是通过数据步骤中的暴力来实现
data work.merged;
merge work.auto
work.auto(rename=(make=make2 mpg=mpg2 rep78=rep2 weight=weight2
foreign=foreign2) firstobs=2);
if make=make2 and mpg=mpg2 and rep78=rep2 and weight=weight2
and foreign NE foreign2 then delete;
if make=make2 and mpg=mpg2 and rep78=rep2 and weight NE weight2
and foreign=foreign2 then delete;
if make=make2 and mpg=mpg2 and rep78 NE rep2 and weight=weight2
and foreign=foreign2 then delete;
if make=make2 and mpg NE mpg2 and rep78=rep2 and weight=weight2
and foreign=foreign2 then delete;
if make NE make2 and mpg=mpg2 and rep78=rep2 and weight=weight2
and foreign=foreign2 then delete;
run;
proc print data=work.merged;
var make mpg rep78 weight foreign;
run;
最后,我们可以使用条件语句比较合并的
变量,以确定哪些变量除一个变量外所有变量都相同
不带var语句的proc print输出:
Obs make mpg rep78 weight foreign make2 mpg2 rep2 weight2 foreign2
1 AMC 22 3 2930 0 AMC 22 3 2930 0
2 AMC 22 3 2930 1 Audi 23 5 2830 1
3 Audi 23 5 2830 1 Audi 23 3 2070 1
4 Audi 23 3 2070 1
我假设您的数据集已经使用
proc sort
进行了排序,这样,除了一个变量外,所有变量都相同的观测值彼此相邻,就像您的示例中那样
data work.merged;
merge work.auto
work.auto(rename=(make=make2 mpg=mpg2 rep78=rep2 weight=weight2
foreign=foreign2) firstobs=2);
x = 0;
if (make=make2) then x + 1;
if (mpg=mpg2) then x + 1;
if (rep78=rep2) then x + 1;
if (weight=weight2) then x + 1;
if (foreign=foreign2) then x + 1;
if x = 4 then delete;
run;
输出:
Obs make mpg rep78 weight foreign make2 mpg2 rep2 weight2 foreign2 x
1 AMC 22 3 2930 0 AMC 22 3 2930 0 5
2 AMC 22 3 2930 1 Audi 23 5 2830 1 1
3 Audi 23 5 2830 1 Audi 23 3 2070 1 3
4 Audi 23 3 2070 1 0
我们将比较
合并的
变量,如果它们相同,则将x
增加1。在这种情况下,我们可以每次将变量x
从0增加到最多5。由于此数据集中有5个变量,因此x=5为最大值,x=0为最小值。如果除了一个之外,所有的都是相同的,那么x=4。在x=4的情况下,我们可以删除它。从您更新的示例中,我认为您需要的是数据集中所有不同的行。这可以使用数据步骤或proc sql完成:
PROC SORT DATA=auto OUT=auto2 NODUPLICATES ;
BY _all_ ;
RUN ;
NODUPLICATES
删除任何重复的行,\u all
指定它检查数据集中的所有字段
proc sql noprint;
create table auto2 as
select distinct *
from auto
;
quit;
*
是一个通配符,用于指定数据集中的所有列,并删除重复行我想我理解你的问题,但我不确定你只保留其中一行是什么意思。你是说只保留三个资产管理公司中的一个还是保留最后两个资产管理公司中的一个?我只想保留两个资产管理公司中的一个,即移除最后两个资产管理公司中的一个。移除后,我将拥有3个AMC中的2个。也许我遗漏了一些东西,但该品牌不应该总是有相同的外国/国内国旗吗?斯科特。不幸的是,在这个例子中它不是。我将发布更相关的例子也。考虑到SAS强大的数据挖掘和处理能力,这应该是相当容易的。好吧,那么您如何判断哪一个是正确的呢?通过基于排序顺序而不是“正确”行计算删除行,您可能会遇到数据完整性问题。但在实际情况中,我有20多个变量,而且变化也很大。好的,我将用一组较短的条件语句添加另一个答案。