Hello,
I have a dataset that looks like this :
id | name | n01 | n02 | n03 | n04 | n05 | n06 |
1 | abcd | a | b | c | d | ||
2 | qw | q | w | ||||
3 | x | x |
I want to separate every character of the "name" variable into the n01 to n06 variables.
Here is what I want it to look like:
id | name | n01 | n02 | n03 | n04 | n05 | n06 |
1 | abcd | a | b | c | d | a | b |
2 | qw | q | w | q | w | q | w |
3 | x | x | x | x | x | x | x |
I already separated every character of the "name" variable into multiple variable with this code (like in the first table)
data want; set have;
length n01-n06 $1;
array n {*} n01-n06;
startpos = 1;
do i = 1 to dim(n);
length_var = vlength(n(i));
n(i) = substr(name, startpos, length_var);
startpos + length_var;
end;
drop i startpos length_var;
run;
I would like to know how to fill until n06 even if the number of character in the "name" variable may vary for each observation.
Thank you for your help. If you need more details, please ask.
You probably want the LENGTH() function and not the VLENGTH() function since you appear to want to ignore the trailing spaces.
This is a good application for the MOD() function.
data want ;
set have (keep=id name);
array _n $1 n01-n06 ;
do _n_=1 to dim(_n) ;
_n(_n_)=char(name,1+mod(_n_-1,length(name)));
end;
run;
Obs id name n01 n02 n03 n04 n05 n06 1 1 abcd a b c d a b 2 2 qw q w q w q w 3 3 x x x x x x x
data have;
infile cards truncover;
input id name $;
cards;
1 abcd
2 qw
3 x
;
data want;
set have;
length _temp_ $100;
array t(*) $1 n01-n06;
_temp_=repeat(compress(name),dim(t)-1);
call pokelong(_temp_,addrlong(t(1)),6);
drop _:;
run;
You probably want the LENGTH() function and not the VLENGTH() function since you appear to want to ignore the trailing spaces.
This is a good application for the MOD() function.
data want ;
set have (keep=id name);
array _n $1 n01-n06 ;
do _n_=1 to dim(_n) ;
_n(_n_)=char(name,1+mod(_n_-1,length(name)));
end;
run;
Obs id name n01 n02 n03 n04 n05 n06 1 1 abcd a b c d a b 2 2 qw q w q w q w 3 3 x x x x x x x
/*linear*/
data want;
set have;
length _temp_ $100;
array t(*) $1 n01-n06;
_temp_=compress(repeat(name,dim(t)-1));
do _n_=1 to dim(t);
t(_n_)=char(_temp_,_n_);
end;
drop _:;
run;
Are you ready for the spotlight? We're accepting content ideas for SAS Innovate 2025 to be held May 6-9 in Orlando, FL. The call is open until September 25. Read more here about why you should contribute and what is in it for you!
Learn how use the CAT functions in SAS to join values from multiple variables into a single value.
Find more tutorials on the SAS Users YouTube channel.