Hi,
I want to create a new variable for which i have var1 as 1 to 20.
if var1 is 1 to 10 then create a new var as var2='first' and from 11 to 20 as var2='Last'.
Can i do this in datastep?
Hi @vraj1,
I see. You "want to create a new variable" in an existing dataset "for which [you] have var1 as 1 to 20."
Whether you really need a new variable (with redundant information!) depends on what you plan to do with it. Maybe it's sufficient to create a format:
proc format;
value grp
1-10 = 'first'
11-20 = 'last';
run;
You can do many things with your existing VAR1 together with this format. For example, perform a frequency count:
proc freq data=have;
format var1 grp.;
tables var1;
run;
If you really need the new variable, you can still create it using the format:
data want;
set have;
var2=put(var1, grp.);
run;
Yes, that is no problem:
data want;
do var1=1 to 20;
var2=ifc(var1<=10,"First","Last");
output;
end;
run;
Not sure why you think you would not be able to do that in a datastep?
Yes, but this step is also doubling the obs.
I want like
id var1 var2
101 1 first
102 2 first
103 19 last
No, it is not doubling the obs:
data have;
input id var1;
cards;
101 1
101 10
101 15
;
run;
title "Dataset HAVE";
proc print;
run;
data want;
set have;
var2=ifc(var1<=10,"First","Last");
run;
title "Dataset WANT";
proc print;
run;
gives this result:
Dataset HAVE Obs id var1 1 101 1 2 101 10 3 101 15 Dataset WANT Obs id var1 var2 1 101 1 First 2 101 10 First 3 101 15 Last
You see, there are the same number of observations in both datasets.
Maybe you need to be more specific with your requirements.
Your requirement states, and I quote:
"I want to create a new variable for which i have var1 as 1 to 20."
Therefore your output dataset will have 20 observations, per my code. If you requirements are not like, please clarify your problem, post test data - in the form of a datastep, and what the output should look like.
Hi @vraj1,
I see. You "want to create a new variable" in an existing dataset "for which [you] have var1 as 1 to 20."
Whether you really need a new variable (with redundant information!) depends on what you plan to do with it. Maybe it's sufficient to create a format:
proc format;
value grp
1-10 = 'first'
11-20 = 'last';
run;
You can do many things with your existing VAR1 together with this format. For example, perform a frequency count:
proc freq data=have;
format var1 grp.;
tables var1;
run;
If you really need the new variable, you can still create it using the format:
data want;
set have;
var2=put(var1, grp.);
run;
Join us for SAS Innovate April 16-19 at the Aria in Las Vegas. Bring the team and save big with our group pricing for a limited time only.
Pre-conference courses and tutorials are filling up fast and are always a sellout. Register today to reserve your seat.
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.