use of the function if nested

Dear members
how to write the command of this function in R

if 0<x<1/2 y=(8/3)*x if 1/2<=x<1 y=(4/3) else y=0

Consider the function case_when() from {dplyr}. It behaves sort of like the SQL equivalent, if you are familiar with that. The same applies for between(), also from {dplyr}.

library(dplyr)

y <- case_when(between(x, 0, 1/2) ~ 8*x/3,
               between(x, 1/2, 1) ~ 4/3,
               TRUE ~ 0)
1 Like

this command doesn't work. I remind you that I work with R-studio 3.6.1

Could you explain why are you saying that command doesn't work? does it produce an error message? It doesn't produce the output you are expecting? if so, what would be that output?

Also, there is no RStudio 3.6.1 version, I think you mean R 3.6.1, which is not the same, take a look to this FAQ to understand the difference.

2 Likes

R has if operator and also else, so you basically can do the same.
See this chapter in advanced R

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