8

I'm trying to concatenate a long string in SAS and it would be helpful to have an inline if function or ternary operator so that I can nest IF statements in the concatenation. I can't find mention of this in the docs. In a DATA step, I'd like to do something like:

myString = "some words " || dead == 1 ? 't' : 'f' || " some more words" ....

Basically, I'm trying to generate some seeds for demonstration Rails app, so that I can dump some SAS data into a SQLite database quickly.

Is there any sort of inline if in SAS?

Clay
  • 2,949
  • 3
  • 38
  • 54

2 Answers2

18

The ifc function (character version, ifn numeric) is the inline if function in SAS. That in SAS would be:

myString = cat("some words ",ifc(dead=1,'t','f')," some more words");

(cat family functions like cat,catx,etc. are more commonly used than the || operator in SAS).

Joe
  • 62,789
  • 6
  • 49
  • 67
  • Great solution! This code solved my problem seamlessly: var2 = ifn(var1 ^= int(var1), 0, 1); – Rodrigo Hjort Sep 04 '21 at 00:11
  • This expression `ifn(var1 ^= int(var1), 0, 1)` is just a convoluted confusing way to code this expression `var1 = int(var1) `. – Tom Oct 06 '21 at 15:40
  • I suspect that it may simply be that they don't know that they can put that on the right hand side of an assignment equal sign - i.e., `var2 = var1 eq int(var1)` (using `eq` for clarity, but `=` would work fine also). But I don't think it's all that confusing, and it is reasonable to use the `ifn` construction (although I do think `ifn(var1 eq int(var1),1,0)` is perhaps more sensible) as the `ifn` makes it a bit easier to read (`x = y = z` can be very confusing and easy to miss which `=` is which). – Joe Oct 06 '21 at 15:51
1

A more traditional SAS way to generate text based on the value of a variable is to define a format.

proc format ;
  value dead 1='dead' 0='alive' other='unknown';
run;
...
myString = catx(' ','some words',put(dead,dead.),'some more words');
Tom
  • 47,574
  • 2
  • 16
  • 29