Why in an if-else statement the assignment operator "=" doesn't execute but "<-" executes?

Hi. I am new to R programming and while I was learning, I was having this doubt.

I would like to know why in an if-else statement the assignment operators "=" and "<-" behaves differently?

The "=" operator doesn't execute the code and showing me an error. But the "<-" operator shows me a result (which is wrong anyways).

When I use the assignment operator I know that the value is being assigned to the variable. In that case, why is it working only for "<-" sign and not "=" sign?

Can you please show the two codes you're describing?

Sure. Here you go.

1- if(x=150){x times 3} else {x times 100} #gives me an error

2- if(x<-150){x times 3} else {x times 100} #executes the code

#for some reason the asterisk sign is not showing in the comment

Both = and <- can be used for assigning a value but they are not identical, as you have seen. Just why isn't important, as neither one is the correct thing to use within the if test. If you want to compare two values, you need to use ==. You will get the result you want with

if(x == 150) {x * 3} else {x * 100}

The asterisk did not appear in your post because that symbol is used for formatting in the text of a post. You can use back ticks to have text interpreted as code. Use one back tick before and after code that is written in line, like this code in line. Use a line with three back ticks just before and after full lines of code.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.