Hi,
I am having a question that I have a variable---code, the values code are so many digits there, such as B11234, B402345, C23456, and F6794321 etc. I want to create a new variable---newcode, with only the first three digits, that are B11, B40, C23, and F67.
Also, how to use array to create a series of newcode1 to newcode10 variables if I have code1, code2, code3..., and code10.
I appreciate any instruction!
Regards,
Hi @CynthiaWei
Maybe you can try this, assuming you have 10 code variables, named code1 code2 etc.
data want;
set have;
array code (10);
array newcode (10) $;
do i=1 to dim(code);
newcode(i) = substr(code(i),1,3);
end;
drop i;
run;
Hope this help
It seems like this is a perfect place to use an ARRAY.
data want;
set have;
array code $ code1-code10;
array newcode $ newcode1-newcode10;
do i=1 to dim(code);
newcode(i)=substr(code(i),1,3);
end;
drop i;
run;
Hi @CynthiaWei
Maybe you can try this, assuming you have 10 code variables, named code1 code2 etc.
data want;
set have;
array code (10);
array newcode (10) $;
do i=1 to dim(code);
newcode(i) = substr(code(i),1,3);
end;
drop i;
run;
Hope this help
Hi @CynthiaWei,
Do you know that many things you can do with the new variables can be done with the existing variables as well by using format $3.?
Examples:
data have;
input (code1-code4) ($) x;
cards;
B11234 B402345 C23456 F6794321 1
B11111 B422222 C23333 F634444 2
;
proc print data=have;
format code: $3.;
run;
proc freq data=have;
format code: $3.;
tables code:;
run;
proc means data=have;
format code1 $3.;
class code1;
var x;
run;
data test;
set have;
format code1 $3.;
by code1 groupformat;
if first.code1;
run;
I really appreciate it! It is very helpful!
With regards,
Also note, if you do decide to create the new variables, the SUBSTR function will only slow the program down. You can get there using:
data want;
set have;
array code $ code1-code10;
array newcode $ 3 newcode1-newcode10;
do i=1 to dim(code);
newcode{i}=code{i};
end;
drop i;
run;
The ARRAY statement is capable of assigning a length to newly created variables in the array.
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
Need to connect to databases in SAS Viya? SAS’ David Ghan shows you two methods – via SAS/ACCESS LIBNAME and SAS Data Connector SASLIBS – in this video.
Find more tutorials on the SAS Users YouTube channel.