here is the table I have
Col_src | A | B | C | D | E | F |
A | 1 | 2 | 3 | 4 | 5 | 6 |
B | 1 | 2 | 3 | 4 | 5 | 6 |
D | 1 | 2 | 3 | 4 | 5 | 6 |
C | 1 | 2 | 3 | 4 | 5 | 6 |
I want to create a column with the value from the respective column indicated in col_src. Please help on solving this.
Col_src | Col_val | A | B | C | D | E | F |
A | 1 | 1 | 2 | 3 | 4 | 5 | 6 |
B | 2 | 1 | 2 | 3 | 4 | 5 | 6 |
D | 4 | 1 | 2 | 3 | 4 | 5 | 6 |
C | 3 | 1 | 2 | 3 | 4 | 5 | 6 |
A Simple VVALUEX perhaps?
data have;
input Col_src $ A B C D E F;
cards;
A 1 2 3 4 5 6
B 1 2 3 4 5 6
D 1 2 3 4 5 6
C 1 2 3 4 5 6
;
data want;
set have;
Col_val=vvaluex(Col_src);
run;
Col_src | A | B | C | D | E | F | Col_val |
---|---|---|---|---|---|---|---|
A | 1 | 2 | 3 | 4 | 5 | 6 | 1 |
B | 1 | 2 | 3 | 4 | 5 | 6 | 2 |
D | 1 | 2 | 3 | 4 | 5 | 6 | 4 |
C | 1 | 2 | 3 | 4 | 5 | 6 | 3 |
No promises without actual data set
data want; set have; array v (*) A B C D E; /* the names of the variables, ALL these must be the same type*/ do i=1 to dim(v); if upcase(col_src) =upcase( vname(v[i])) then col_val=v[i]; end; drop i; run;
The UPCASE I am using because it is not clear exactly the values of col_src might be, assuming the "example" is simplified from your actual data, and the Vname function may return the name of the variable id a different case than you expect.
If your Col_src and variable names have any spelling difference other than case then you need to provide a much more detailed example because character comparisons may be a tad more complex than you expect.
A Simple VVALUEX perhaps?
data have;
input Col_src $ A B C D E F;
cards;
A 1 2 3 4 5 6
B 1 2 3 4 5 6
D 1 2 3 4 5 6
C 1 2 3 4 5 6
;
data want;
set have;
Col_val=vvaluex(Col_src);
run;
Col_src | A | B | C | D | E | F | Col_val |
---|---|---|---|---|---|---|---|
A | 1 | 2 | 3 | 4 | 5 | 6 | 1 |
B | 1 | 2 | 3 | 4 | 5 | 6 | 2 |
D | 1 | 2 | 3 | 4 | 5 | 6 | 4 |
C | 1 | 2 | 3 | 4 | 5 | 6 | 3 |
It's finally time to hack! Remember to visit the SAS Hacker's Hub regularly for news and updates.
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.