Inserting Columns into SAS Datasets

Accepted Solution Solved
Reply
Frequent Contributor
Posts: 121
Accepted Solution

Inserting Columns into SAS Datasets

Does anyone know if there is a way (ie SAS command) to insert a new variable between existing SAS variables in a dataset?

For example I have the following dataset......

Name     Age

Tom         10

John        18

Jill            23

Chris        25

Don          31

......and I want to end up with the dataset below.

Name     Sex     Age

Tom         M        10

John        M        18

Jill            F         23

Chris        M        25

Don          M        31


Accepted Solutions
Solution
‎09-05-2014 12:21 PM
Trusted Advisor
Posts: 1,228

Re: Inserting Columns into SAS Datasets

Try retain statement after adding variable to your existing dataset.

data want;

retain Name Sex  Age;

set have;

run;

View solution in original post


All Replies
Trusted Advisor
Posts: 1,137

Re: Inserting Columns into SAS Datasets

if you have another dataset with name and sex variables , then you can use the merge statement to combine the age dataset with gender dataset by name variable and you can get the three variables in a single dataset.

something like

data want;

merge age gender;

by name;

run;

Thanks,

Jag

Thanks,
Jag
Solution
‎09-05-2014 12:21 PM
Trusted Advisor
Posts: 1,228

Re: Inserting Columns into SAS Datasets

Try retain statement after adding variable to your existing dataset.

data want;

retain Name Sex  Age;

set have;

run;

Regular Contributor
Posts: 233

Re: Inserting Columns into SAS Datasets

What ever


Frequent Contributor
Posts: 121

Re: Inserting Columns into SAS Datasets

Hima,

There is no relationship per se. I have a dataset that already contains the Name and Age variables and I am trying to create/generate a new variable (Sex) between the two existing ones. I was hoping that there is a way to do this in SAS, similar to how you can insert a new column in Excel and fill it in with values.

I know how to create a new variable at the end of the variables in my existing dataset, but I was hoping to be able to create it betweent the two existing ones.

Regular Contributor
Posts: 233

Re: Inserting Columns into SAS Datasets

Thank you so much. I created a scenario to myself as per your explanation. Please adjust it your needs. What stat@sas provided works great in the situation.

DATA HAVE;
INPUT NAME $    AGE;
DATALINES;
TOM         10
JOHN        18
JILL        23
CHRIS       25
DON         31
;
RUN;

DATA WANT;
RETAIN NAME SEX AGE;
SET HAVE;

IF INDEX(NAME,'O') THEN
  SEX='M';
ELSE SEX='F';
RUN;

Capture.JPG

🔒 This topic is solved and locked.

Need further help from the community? Please ask a new question.

Discussion stats
  • 5 replies
  • 297 views
  • 7 likes
  • 4 in conversation