Hi everybody,
I am a new SAS user and I'd need your help.
I have a dataset having a single variable with multiple rows in each of which a string is contained.
This last must be divided according to a given positions and length, this data (positions and length) are contained in another dataset.
Example:
Dataset containing positions and length:
Length | Position |
2 | 1 |
1 | 3 |
8 | 4 |
Dataset to be divided:
VAR1 |
abc0123def0 |
kol1256oiu1 |
The solution I found is to use the substr function for each variable, writing manually the positions and length:
data output;
set input;
var_1=substr(VAR1, 1, 2);
var_1=substr(VAR1, 3, 1);
var_1=substr(VAR1, 4, 8);
drop VAR1;
run;
but this method is slow, is there a faster and more automatic method?
Thank you 🙂
Ok. Try this
data one;
input Length Position;
datalines;
2 1
1 3
8 4
;
data two;
input var1 :$12.;
datalines;
abc0123def0
kol1256oiu1
;
proc sql noprint;
select count(*) into :d separated by ''
from one;
quit;
data want(keep = var:);
set two;
v = Var1;
do i = 1 to n;
set one point = i nobs = n;
array var {&d.};
var[i] = substr(v, Position, Length);
end;
run;
Do you want this to be split into separate variables or observations ?
Thanks for the reply, I'd be interested in spitting the dataset into separate variables.
Ok. Is it always three variables? Or can that vary?
It can vary.
Ok. Try this
data one;
input Length Position;
datalines;
2 1
1 3
8 4
;
data two;
input var1 :$12.;
datalines;
abc0123def0
kol1256oiu1
;
proc sql noprint;
select count(*) into :d separated by ''
from one;
quit;
data want(keep = var:);
set two;
v = Var1;
do i = 1 to n;
set one point = i nobs = n;
array var {&d.};
var[i] = substr(v, Position, Length);
end;
run;
WOW this is great!!! This code works on my original data, thank you 😊
Anytime, glad to help 🙂
If observations :
data one;
input Length Position;
datalines;
2 1
1 3
8 4
;
data two;
input VAR1 :$12.;
datalines;
abc0123def0
kol1256oiu1
;
data want(keep = var2);
set two;
do i = 1 to n;
set one point = i nobs = n;
var2 = substr(var1, Position, Length);
output;
end;
run;
SAS Innovate 2025 is scheduled for May 6-9 in Orlando, FL. Sign up to be first to learn about the agenda and registration!
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.
Ready to level-up your skills? Choose your own adventure.