Hello All,
The below program using substr extracts last 3 values from obs, can anyone please help me to undersatnad the logic using substr function
input trt $;
cards;
treat123
treat21
treat1
treat1
trea2
lbdate
;run;
data abc;
set temp;
a=reverse(substr(left(reverse(trt)),1,3));
b=substr(trt,length(trt)-2);
run;
Thanks
Which of these do you already understand?
For that piece of the puzzle ...
The second parameter within SUBSTR is a number that indicates which character to begin with.
When the third parameter is omitted (as is the case here), SUBSTR takes all the remaining characters.
So this code says measure the length of the incoming string. Substract 2 from that. That becomes the starting position. This means that there will be 3 characters available (as long as the length of the original string is at least 3 characters). Better code would be:
if length(trt) >= 3 then b = substr(trt, length(trt)-2);
That protects against calculating a negative starting position, something that SUBSTR would complain about.
Good time to read the manual methinks, substr is clearly described there.
If you just want the numbers at the end (and they don't appear anywhere else in the string) compress is simpler:
data want; text="abcd123"; num=compress(text," ","kd"); run;
@tinayong wrote:
output of the program
123
t21
at1
at1
ea2
ate
b=substr(trt,length(trt)-2);
length of the variabke is 8 and 8-2 =6,
so for the first observation from the sixth position we get the values using substr function
but from the second observation onwards the obs values decreasing but still substr function extracting last 3 values
So am missing some logic here, may be am not thinking correct way
Perhaps you phrased your question incorrectly. If you are wanting the numbers at the end and not the "last 3 values" then @RW9 has your solution with compress function
Well one method is:
data want;
trt="treat123";
want=substr(trt,lengthn(trt)-2);
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.