SAS BASICO Giampaolo Orlandoni Josefa Ramoni Instituto de Estadística Aplicada Universidad de Los Andes Venezuela
SASBASICO
Giampaolo Orlandoni Josefa Ramoni
Instituto de Estadística Aplicadap
Universidad de Los AndesVenezuela
COMBINACION DE DATA SETS
1. CONCATENACION (CONCATENATING)
2. INTERCALADO ORDENADO(INTERLEAVING)
3. COMBINACION (MERGING)
4. ACTUALIZACION (UPDATING)
Subconjuntos de Datos
To work with a subset of a SAS data set, you may need to select observations, variables, or both. In the DATA step, there is a number of tools for subsetting data.p, g
•Subsetting IF statements to select only those observations that meet a specified condition
•IF-THEN/ELSE constructs with DELETE and OUTPUT statements to delete or select observations that
t diti ti l meet a condition, respectively
•DROP= and KEEP= data set options and DROP and KEEP statements to drop or keep selected variables statements, to drop or keep selected variables
•WHERE statements to select only those observations that meet a specified condition (under certain that meet a specified condition (under certain circumstances).
Data Nomina;I fil 'C \D t S \d t\ l i d t'
CREACION de SUBCONJUNTOS DATOS. If-Then-Else
Infile 'C:\DataSas\dat\salario.dat';Input IdN $ 1-4 Apellido $ 9-19 Nombre $ 20-29 Ciudad $ 30-42 Estado $ 43-44 / Sexo $ 1 Cod $ 9-11 Salario 20-29 @30 FNac date7. @43 FCnt date7. Telef $ 54-65;@30 FNac date7. @43 FCnt date7. Telef $ 54 65;Format FNac FCnt date7.;
If Cod='ME1' then Grupo='Mecan1'; else if cod='ME2' then Grupo='Mecan2'; else if cod= ME2 then Grupo= Mecan2 ; else if cod='PT1' or cod='PT2' thenGrupo='Pintor';l G 'Ot 'else Grupo ='Otros';
Proc print; run;
Data Salario; Set Nomina(drop=sexo FNac FCnt);if salario >60000 then Categ='C_Alto';else if salario <30000 then Categ='C_Bajo';else Categ='C_Media';
Proc print; run; \2_1-SalarioInfile.sas
Data Nomina;Infile 'C:\DataSas\dat\salario dat';
Ejemplo: SalarioInfile.sas
Infile 'C:\DataSas\dat\salario.dat';Input IdN $ 1-4 Apellido $ 9-19 Nombre $ 20-29 Ciudad $ 30-42 Estado $ 43-44 / Sexo $ 1 Cod $ 9-11 Salario 20 29 @30 FNac date7 @43 FCnt date7 Telef $ 54 65;20-29 @30 FNac date7. @43 FCnt date7. Telef $ 54-65;Format FNac FCnt date7.;
/*Segmentando Conjuntos de datos. If segmenta */;
Data SalarioOtros;;Set Salario;
if Grupo='Otros';if Sexo= 'M';if Sexo= M ;if salario > 20000 and salario < 60000;
Proc print data=SalarioOtros; run;
2_1-SalarioInfile.sas
WHERE. Comparaciones Múltiplesó á•Selección de observaciones basada en más de
una comparación•Comparaciones compuestas: p p
•AND: verificar dos condiciones•OR: verificar al menos una condición
Ejemplos: AND: proc print data=ventas noobs;
var Vendedor Mes Cantidad Venta;
Where Vendedor ='Garcia‘ and Month=‘01’;
OR: proc print data=ventas noobs;
var Vendedor Mes Cantidad Venta;
Where VendedorCantidad>500 or Venta>20000;
WHERE. Totales de Grupos•Pueden suprimirse los subtotales, mediante el p ,uso de SUMBY.•Sólo se admite una variable SUMBY, que debe aparecer también en BY PROC PRINT calcula aparecer también en BY. PROC PRINT calcula sumas cuando ocurren cambios en el valor de:
•variable SUMBYl i i bl BY ifi d t •cualquier variable en BY especificado antes
de la variable SUMBY•Ejemplo:
proc print data=Ventas;var Cantidad Venta; where Cantidad>500 or Venta>20000;format Cantidad comma7. Venta dollar14.2;sum Cantidad Venta;by Vendedor Mes; id Vendedor Mes;sumby Vendedor;
WHERE. Observaciones en Páginas Separadas
Reportes con múltiples secciones en páginas separadas, mediante PAGEBY
i dproc print data=Ventas;
var Cantidad Venta;
where Cantidad>500 or Venta>20000;
format Cantidad comma7. Venta dollar14.2;
sum Cantidad Venta;
by Vendedor Mes; by Vendedor Mes;
id Vendedor Mes;
sumby Vendedor;sumby Vendedor;
pageby Vendedor;
1-CONCATENACION Data Sets
•Usar SET en el Data StepNúmero total de Observaciones en el Data Set Final (DSF) es
1-Concatenación de DS. Igual Número de Variables
•Número total de Observaciones en el Data Set Final (DSF) esigual a la suma de observaciones en los DS que se combinan•Número de Variables en el DSF: Igual al número de diferentesvariables en los DS que se combinan.variables en los DS que se combinan.
•Ejemplo: 2_CombinarSET_1.sas
1. Data Dep1; Input Nombre $ Edad Sexo $ Sueldo;2. Data Dep2; Input Nombre $ Edad Sexo $ Sueldo;3. Data Dep1_2; Set Dep1 Dep2;
Proc Print data=Dep1_2; Title 'Dep1 y Dep2‘;
Concatenación de archivos
A1A1NOMBRE SEXO CODIGO
JUAN M NA1
A2A2NOMBRE SEXO CODIGO
JUAN M NA1LUISA F NA1RAUL M NA1SAUL M NA1 JULIA F NA1
NORA F NA2RAUL M NA2
JULIA F NA1
Data NUEVO;SET A1 A2SET A1 A2;
run;
NOMBRE SEXO CODIGONOMBRE SEXO CODIGO
Concatenación de archivos
A1 A2
NOMBRESEXO CODIGO
NOMBRE SEXO CODIGO
Data c;SET A1 A2;
run;
A1
A2A2
NOMBRE SEXO CODIGO
CONCATENACION Data Sets. IGUAL Número de Variables
Obs Nombre Edad Sexo Sueldo
1-Data Dep1
Obs Nombre Edad Sexo Sueldo
1 Vincente 34 M 1000
2 Felipe 28 M 2000
3 Tomas 27 M 1800
Obs Nombre Edad Sexo Sueldo
1 Vincente 34 M 1000
3-Data Dep1_2
3 Tomas 27 M 1800
4 Nicolas 36 M 3000
5 Gisela 32 F 3500
6 Humberto 39 M 1900
2 Felipe 28 M 2000
3 Tomas 27 M 1800
4 Nicolas 36 M 3000
5 Gisela 32 F 35006 Humberto 39 M 1900
7 Emily 22 F 2600
8 Michaela 32 F 2500
6 Humberto 39 M 1900
7 Emily 22 F 2600
8 Michaela 32 F 2500
9 Martin 40 M 3500
Obs Nombre Edad Sexo Sueldo
1 Martin 40 M 3500
9 Martin 40 M 3500
10 Maria 45 F 4500
11 Odilia 28 F 2975
12 Tomas 33 M 2750
2-Data Dep2
2 Maria 45 F 4500
3 Odilia 28 F 2975
4 Tomas 33 M 2750
13 Luis 38 M 3390
14 Benito 29 M 2800
15 Francisc 41 M 3500
5 Luis 38 M 3390
6 Benito 29 M 2800
7 Francisc 41 M 3500
Data Dep1_2;Set Dep1 Dep2;run;
2-Diferente Número de Variables:
CONCATENACION Data Sets
•Número total de Observaciones en el Data Set Final (DSF) es
igual a la suma de observaciones en los DS que se combinan
•Número de Variables en el DSF: Igual al número de
diferentes variables en los DS que se combinan.
•Ejemplo: 2_CombinarSET_2,sas:
1. Data Dep1; Input Nombre $ Edad Sexo $ Sueldo;1. Data Dep1; Input Nombre $ Edad Sexo $ Sueldo;2. Data Dep2; Input Nombre $ Edad Sexo $;3. Data Dep1_2; Set Dep1 Dep2;
•El DS contiene todas las variables:
Nombre$ Edad Sexo$ Sueldo
•Se generan datos faltantes para las observaciones que no
tienen información de alguna variable.
Las variables deben tener los mismos atributos (mismo tipo). De lo contrario la concatenación no se realiza y el programa De lo contrario la concatenación no se realiza y el programa produce un error.
Ejemplo: Edad numérica en Dep1 j p pEdad alfanumérica en Dep2
ERROR: La variable Edad se ha definido como alfanumérica y como numérica.y
***Combine tables by rows (Concatenate tables by Append method)***;Combine tables by rows (Concatenate tables by Append method) ;
Data COMBINAD0;length NOMBRE $ 10 EDAD 8 SEXO $ 8 SUELDO 8;length NOMBRE $ 10 EDAD 8 SEXO $ 8 SUELDO 8;set Work.Dep1
Work.Dep2 ;keep NOMBRE EDAD SEXO SUELDO;keep NOMBRE EDAD SEXO SUELDO;run;
CONCATENACION Data Sets. DISTINTO NUMERO DE VARIABLES
Ob b d d S S ld
1-Data Dep1Obs Nombre Edad Sexo Sueldo
1 Vincente 34 M 1000
2 Felipe 28 M 2000
3 Tomas 27 M 1800
3-Data Dep1_2Obs Nombre Edad Sexo Sueldo
3 Tomas 27 M 1800
4 Nicolas 36 M 3000
5 Gisela 32 F 3500
6 Humberto 39 M 1900
1 Vincente 34 M 1000
2 Felipe 28 M 2000
3 Tomas 27 M 1800
4 Nicolas 36 M 30006 Humberto 39 M 1900
7 Emily 22 F 2600
8 Michaela 32 F 2500
5 Gisela 32 F 3500
6 Humberto 39 M 1900
7 Emily 22 F 2600
8 Michaela 32 F 2500
Obs Nombre Edad Sexo
1 Martin 40 M
2-Data Dep2 9 Martin 40 M .
10 Maria 45 F .
11 Odilia 28 F .
12 Tomas 33 M .2 Maria 45 F
3 Odilia 28 F
4 Tomas 33 M
12 Tomas 33 M .
13 Luis 38 M .
14 Benito 29 M .
15 Francisco 41 M .
5 Luis 38 M
6 Benito 29 M
7 Francisc 41 M
Data Dep1_2;Set Dep1 Dep2;run;
Los DS deben estar ordenados por la misma
2-INTERCALADO (INTERLEAVE) Data SetsLos DS deben estar ordenados por la mismavariable especificada en el BY que acompañaal comando SET
proc sort data=Work.Dep1 out=WORK.TABLA1;by SEXO; run;by SEXO; run;
proc sort data=Work.Dep2 out=WORK.TABLA2;by SEXO; run;by SEXO; run;
data COMBINA;length NOMBRE $ 10 EDAD 8 SEXO $ 8 SUELDO 8;set WORK.TABLA1 WORK.TABLA2 ;by SEXO;keep NOMBRE EDAD SEXO SUELDO; run;
•Combina observaciones de dos o más DS en una solab ió DS
3-MERGE Data Sets
observación y en un nuevo DS.•El nuevo DS contiene todas las variables de los DSoriginales
1-Merge One-to-one: 2MergeOne.sas
•No se usa el BY.•Observaciones se combinan según su posición en el DSinput.•El número de observaciones en el nuevo DS es igual aln_maximo =max(n1,n2)•Ejemplo:
1. Data Clase; Input Nombre $ 1‐25 An $ 26‐30 Espec $ 33‐50;2 Data Horario; Input Fecha date9 @12 Hora $ @19 Sala $;2. Data Horario; Input Fecha date9. @12 Hora $ @19 Sala $;3. Data Cronograma; Merge Clase Horario;
Ejemplo: asignación de horarios de sala de conferencias aestudiantes
MERGE One-to-One. 2MergeOne.sas
estudiantes
•Nombre: nombre estudiante.An: año estudio: 1° 2° 3° 4°•An: año estudio: 1 , 2 , 3 , 4
•Especialidad: area de especialización (valor faltante para1° y 2° años).
Programa: El siguiente programa ejecuta un Merge One-to-One de los DS, asignando un horario a cada estudiante dela clase en el orden de los datosla clase en el orden de los datos
•data Clase; Input Name $ 1-25 Year $ 26-34 Spec $ 36-50;
•data Horario; Input Date date9. @12 Time $ @19 Room $;
•data cronograma; merge clase horario;
Clase
Merge One-to-One
Obs Nombre An Espec
1 Azuaje, Juan prim
2 Carter, Tomas terc ArteObs Nombre An Espec Fecha Hora Sala
Cronograma = Clase + Horario
3 Perez, Elisa cuar Matematica
4 Tamayo, Raquel prim
5 Uzon, Rolando segn
1 Azuaje, Juan
prim 14SEP2010 10:00 103
2 Carter, Tomas
terc Arte 14SEP2010 10:30 103
6 Wiky, Mauricio terc Arte 3 Perez, Elisa
cuar Matematica 14SEP2010 11:00 207
4 Tamayo, Raquel
prim 15SEP2010 10:00 105
Obs Fecha Hora Sala
1 14SEP2010 10 00 103
5 Uzon, Rolando
segn 15SEP2010 10:30 105Horario
1 14SEP2010 10:00 103
2 14SEP2010 10:30 103
3 14SEP2010 11:00 207
4 15SEP2010 10:00 105
6 Wiky, Mauricio
terc Arte 17SEP2010 11:00 207
4 15SEP2010 10:00 105
5 15SEP2010 10:30 105
6 17SEP2010 11:00 207
Se usa BY para combinar observaciones provenientes de
2-Merge Match: 2MergeMatch.sasp p
los DS input data, basados en en valores comunes de lavariable por la que se unen (merge) los DS.
MERGE SAS-data-set-list;BY variable-list;
Ejemplo:1-Data Dep1; Input Nombre $ 1-10 Edad Sexo $ Sueldo;Sueldo;proc sort data=Dep1 out=WORK.Tabla1; by SEXO; 2-Data Dep2; Input Nombre $ 1-10 Edad Sexo $ Sueldo;proc sort data=Dep2 out=WORK.Tabla2; by SEXO; 3-Data Dep1_2_Merge1;
Merge WORK.Tabla1 WORK.Tabla2; By Sexo;
Una compañía mantiene dos Sas DS: COMPANY y FINANZA.
MERGE Match Data Sets
Data Set Variable
COMPAÑÍANombre
EdadEdad
Sexo
NombreFINANZA Id
Sueldo
1-Data Company; Input Nom $ 1-25 Edad 27-28 Sexo $ 30;proc sort data=company; by Nom;
2-Data Finanza; Input IdNum $ 1-11 Nom $ 13-40 Sueldo;proc sort data=finanza; by Nom;
3-Data CompaFina;Merge company finanza; by nom;
Combinación de archivos
VUELOVUELOVUELO PASAJERO DESTINO
PRECIOSPRECIOSDESTINO CIUDAD PRECIO
921 169 DFW982 120 DFW114 185 LAX431 103 LAX
DFW Dallas 600FRA Frankfurt 1200LAX Los Angeles 900LON London 900
data Ingreso(keep= vuelo ciudad ingreso);MERGE vuelo precios;p ;By destino;ingreso=pasajeros*precio;
Run;Run;
VUELO PASAJERO DESTINO CIUDAD PRECIOVUELO PASAJERO DESTINO CIUDAD PRECIO
•Reemplaza valores de variables del MasterDS con
4-UPDATING Data Sets
valores no faltantes del TransactionDS.•Se trabaja con dos DS:
•Master DS: conjunto original de datosj g•Transaction DS: contiene la información nueva queva a reemplazar la información antigua contenidaen el Master.e e aste
Foma general:
Update masterDS transactionDS;BY variable identificadora;
•Update sólo puede manejar dos DSEl d BY i di l i bl t h•El comando BY indica las variables match
•Ambos DS deben estar ordenados por las mismasvariables match especificadas en BY.
Statement/Procedure Action Performed
•Controls the operation of a SET, MERGE, UPDATE, or MODIFY statement in the DATA step and sets up special grouping
BY variables. •BY-group processing is a means of processing observations that have the same values of one or more variables.
MERGE
•Reads observations from two or more SAS DS and joins them into a single observation.•When using MERGE with BY, the data must be sorted or indexed on the BY variable.the BY variable.
MODIFY
•Processes observations in a SAS data set•Sorted or indexed data are not required for use with BY, but are recommended for performance in place (Contrast with are recommended for performance in place. (Contrast with UPDATE.)
SET •Reads observations from one or more SAS data sets.
UPDATE
•Applies transactions to observations in a master SAS data set. UPDATE does not update observations in place; it produces an updated copy of the current data set.•Both the master and transaction DS must be sorted by or indexed yon the BY variable.
PROC APPEND •Adds observations from one SAS DS to the end of another SAS DS