I'm trying to learn arrays in SAS. In the example below I am using the sashelp.cars data set and converting mpg_city and mpg_highway into km.
1. How would I rename the variables to kmpg_city and kmpg_highway?
2. And, how would I create new variables called kmpg_city and kmpg_highway, so that I can keep the mpg_city and mpg_highway variables in the dataset?
Without using an array I would just do this:
kmpg_city = mpg_city*1.6
kmpg_highway = kmpg_highway*1.6
data want;
set sashelp.cars;
/* Array statement (i.e., ARRAY) */
/* Array name (e.g., array_name) */
/* Number of elements (i.e., the number of vars. (*) tells SAS to figure it out) */
/* Elements (i.e., the vars) */
ARRAY array_name(*) mpg_city mpg_highway ;
/* DO loop specifies the index variable and tells SAS how many iterations thru the loop. */
/* DIM tells SAS to figure out the number of iterations based on the number of elements. */
DO index_var = 1 to DIM (array_name);
/* The syntax you want. */
/* Write the syntax for 1 variable, then substitute the array name followed by the index var name in squiggly brackets. */
array_name {index_var} = array_name {index_var}*1.6;
END;
run;
Thanks!
It doesn't sound like you want to RENAME anything. Instead it sounds like you want to make NEW variables.
So use TWO arrays. One for the original variables and one for the new variables.
data want;
set have;
array original mpg_city mpg_highway;
array new kpg_cit kpg_highway;
do index=1 to dim(original);
new[index] = 1.6 * original[index];
end;
run;
It doesn't sound like you want to RENAME anything. Instead it sounds like you want to make NEW variables.
So use TWO arrays. One for the original variables and one for the new variables.
data want;
set have;
array original mpg_city mpg_highway;
array new kpg_cit kpg_highway;
do index=1 to dim(original);
new[index] = 1.6 * original[index];
end;
run;
Thank you. I will check this out.
To clarify, I'd like to learn how to rename variables processed in an array AND create new variables in an array.
Arrays cannot be used to rename variables.
@Tom has already shown how to create new variables.
Nearly 200 sessions are now available on demand in the Innovate Hub.
Watch Now →SAS' Charu Shankar shares her PROC SQL expertise by showing you how to master the WHERE clause using real winter weather data.
Find more tutorials on the SAS Users YouTube channel.