Why does this optoisolator circuit behave like that?
Do the math.

The output is driving 16 V across 4.7 k&Omega;, so is passing 3.4 mA.

On the input there is 5 V across 150 &Omega; and the LED.  According to the 4N25 datasheet, the forward drop of the LED can be 1.5 V.  The current is therefore ((5 V) - (1.5 V)) / (150 &Omega;) = 23 mA.

You are getting a current transfer ratio of (3.4 mA)/(23 mA) = 15%.   Now again look in the datasheet and see that the minimum guaranteed CTR is 20%.  Something is therefore not as expected.

The most likely culprit is that the digital output is not really 5 V when you try to draw 23 mA from it.  That's a lot to expect a digital output to do.  Check its datasheet.

Let's say for example (your job to look up the actual value), that the digital output can source 10 mA and drop to no less than 4.5 V in the process.  After the 1.5 V drop across the LED, the resistor must be at least (3.0 V)/(10 mA) = 300 &Omega;.

Now let's look at what the output should be for this example.  With 10 mA in and 20% CTR, you can expect 2 mA output current.  To drive a resistor all the way to 18 V, the resistor must be at least (18 V)/(2 mA) = 9 k&Omega;.

So change R1 to 300 &Omega; and R2 to 10 k&Omega;, and everything should work for this made-up example.  Look in the datasheet to see what the actual digital output source current and voltage at that current are, and plug in the numbers for your case.