El script compara los comportamientos de los diferentes métodos para añadir datos. Examina el paso DATA con la instrucción SET, los operadores de conjuntos de PROC SQL (UNION, UNION ALL, UNION CORR, OUTER UNION) y el procedimiento PROC DATASETS con la instrucción APPEND. Destaca la gestión de duplicados, la alineación de columnas (nomenclatura diferente) y el uso de la opción FORCE cuando las estructuras de las tablas difieren.
Análisis de datos
Type : MIXTE
Los datos se derivan de la tabla del sistema 'sashelp.class' para la tabla 'big', y se crean manualmente a través de un DATA Step para la tabla 'small'.
1 Bloque de código
DATA STEP Data
Explicación : Creación de dos tablas de trabajo: 'big' (extraída de sashelp.class con duplicación intencional) y 'small' (una sola fila con nombres de columna/orden diferentes para simular incompatibilidades estructurales).
¡Copiado!
title '2.8 Appending Data Sets';
* Create a not so big data set;
data big;
set sashelp.class(keep=name sex age height weight);
where name > 'L';
output big;
* create a duplicate for Mary;
if name=:'M' then output big;
run;
data small;
* The variable WEIGHT has been misspelled as WT;
* The variables WT and HEIGHT are out of order;
name='fred'; sex='m'; age=5; wt=45; height=30;
run;
1
title '2.8 Appending Data Sets';
2
* Create a not so big data set;
3
DATA big;
4
SET sashelp.class(keep=name sex age height weight);
5
where name > 'L';
6
OUTPUT big;
7
* create a duplicate for Mary;
8
IF name=:'M'THENOUTPUT big;
9
RUN;
10
DATA small;
11
* The variable WEIGHT has been misspelled as WT;
12
* The variables WT and HEIGHT are out of order;
13
name='fred'; sex='m'; age=5; wt=45; height=30;
14
RUN;
2 Bloque de código
DATA STEP Data
Explicación : Concatenación simple usando el paso DATA y la instrucción SET. Esto apila las dos tablas. Las columnas presentes en una pero no en la otra (como 'wt') tendrán valores faltantes en las filas provenientes de la tabla donde están ausentes.
¡Copiado!
title2 'Using the SET Statement';
* Append using the SET statement;
data bigger;
set big small;
run;
proc print data=bigger;
run;
1
title2 'Using the SET Statement';
2
* Append using the SET statement;
3
DATA bigger;
4
SET big small;
5
RUN;
6
PROC PRINTDATA=bigger;
7
RUN;
3 Bloque de código
PROC SQL Data
Explicación : Uso del operador SQL UNION. Este método concatena los resultados pero elimina las filas que son duplicados exactos (comportamiento predeterminado de UNION).
¡Copiado!
title2 'Using SQL UNION';
* Append using UNION;
proc sql noprint;
create table bigger as
select *
from big
union
select *
from small;
quit;
proc print data=bigger;
run;
1
title2 'Using SQL UNION';
2
* Append using UNION;
3
PROC SQL noprint;
4
create TABLE bigger as
5
select *
6
from big
7
union
8
select *
9
from small;
10
QUIT;
11
PROC PRINTDATA=bigger;
12
RUN;
4 Bloque de código
PROC SQL Data
Explicación : Uso de SQL UNION ALL. A diferencia de UNION simple, UNION ALL conserva todas las filas, incluyendo los duplicados.
¡Copiado!
title2 'Using SQL UNION ALL';
* Append using UNION;
proc sql noprint;
create table bigger as
select *
from big
union all
select *
from small;
quit;
proc print data=bigger;
run;
1
title2 'Using SQL UNION ALL';
2
* Append using UNION;
3
PROC SQL noprint;
4
create TABLE bigger as
5
select *
6
from big
7
union all
8
select *
9
from small;
10
QUIT;
11
PROC PRINTDATA=bigger;
12
RUN;
5 Bloque de código
PROC SQL Data
Explicación : Uso de UNION ALL con renombramiento explícito de la columna 'wt' a 'Weight' en la segunda consulta para alinear las estructuras de datos.
¡Copiado!
title2 'Using SQL UNION ALL';
title3 'Naming the Variables';
* Append using UNION ALL;
proc sql noprint;
create table bigger as
select *
from big
union all
select Name,Sex,Age,Height,wt as Weight
from small;
quit;
proc print data=bigger;
run;
1
title2 'Using SQL UNION ALL';
2
title3 'Naming the Variables';
3
* Append using UNION ALL;
4
PROC SQL noprint;
5
create TABLE bigger as
6
select *
7
from big
8
union all
9
select Name,Sex,Age,Height,wt as Weight
10
from small;
11
QUIT;
12
PROC PRINTDATA=bigger;
13
RUN;
6 Bloque de código
PROC SQL Data
Explicación : Uso del operador UNION CORR (CORResponding). SAS asocia las columnas por su nombre y no por su posición. Las columnas que no existen en ambas tablas se excluyen del resultado.
¡Copiado!
title2 'Using SQL UNION CORR';
* Append using UNION;
proc sql noprint;
create table bigger as
select *
from big
union corr
select *
from small;
quit;
proc print data=bigger;
run;
1
title2 'Using SQL UNION CORR';
2
* Append using UNION;
3
PROC SQL noprint;
4
create TABLE bigger as
5
select *
6
from big
7
union corr
8
select *
9
from small;
10
QUIT;
11
PROC PRINTDATA=bigger;
12
RUN;
7 Bloque de código
PROC SQL Data
Explicación : Uso de OUTER UNION. Este operador realiza una unión completa sin intentar superponer columnas si no coinciden, aunque en un contexto SAS SQL simple, a menudo se parece a un 'append' permisivo.
¡Copiado!
title2 'Using SQL OUTER UNION';
* Append using UNION;
proc sql noprint;
create table bigger as
select *
from big
outer union
select *
from small;
quit;
proc print data=bigger;
run;
1
title2 'Using SQL OUTER UNION';
2
* Append using UNION;
3
PROC SQL noprint;
4
create TABLE bigger as
5
select *
6
from big
7
outer union
8
select *
9
from small;
10
QUIT;
11
PROC PRINTDATA=bigger;
12
RUN;
8 Bloque de código
PROC DATASETS
Explicación : Uso de PROC DATASETS con la instrucción APPEND para añadir datos directamente a la tabla base ('big') sin recrear toda la tabla. El primer intento falla porque las estructuras (nombres/tipos de variables) difieren. El segundo tiene éxito gracias a la opción FORCE, que fuerza la adición truncando las variables demasiado largas o ignorando aquellas que no están en la tabla base.
¡Copiado!
title2 'Using the APPEND Statement';
* Append using the APPEND Statement;
* This step fails because of mismatched PDVs;
proc datasets library=work nolist;
append base=big data=small;
quit;
* Use the FORCE option;
proc datasets library=work nolist;
append base=big data=small force;
quit;
proc print data=big;
run;
1
title2 'Using the APPEND Statement';
2
* Append using the APPEND Statement;
3
* This step fails because of mismatched PDVs;
4
PROC DATASETS library=work nolist;
5
append base=big DATA=small;
6
QUIT;
7
8
* Use the FORCE option;
9
PROC DATASETS library=work nolist;
10
append base=big DATA=small force;
11
QUIT;
12
PROC PRINTDATA=big;
13
RUN;
Este material se proporciona "tal cual" por We Are Cas. No hay garantías, expresas o implícitas, en cuanto a la comerciabilidad o idoneidad para un propósito particular con respecto a los materiales o el código contenidos en este documento. We Are Cas no es responsable de los errores en este material tal como existe ahora o existirá, ni We Are Cas proporciona soporte técnico para el mismo.
SAS y todos los demás nombres de productos o servicios de SAS Institute Inc. son marcas registradas o marcas comerciales de SAS Institute Inc. en los EE. UU. y otros países. ® indica registro en los EE. UU. WeAreCAS es un sitio comunitario independiente y no está afiliado a SAS Institute Inc.
Este sitio utiliza cookies técnicas y analíticas para mejorar su experiencia.
Saber más.