Simple if then Statement

I am fairly new to R and have tried several versions of the following statement with no avail. What I need is to create a new variable MAXVO2 and perform calculations adjusted for Age and Sex and then round it to 2 decimals.

If (18 <= ed.frame$Age && ed.frame$Age <= 99 && ed.frame$Sex == 1) {
ed.frame$MAXVO2 <- 60-(.55ed.frame$Age)
if(18 <= ed.frame$AgeAge && ed.frame$Age <= 99 && Sex = 2) {
ed.frame$MAXVO2 <- 48-(.37
Else {ed.frame$MAXVO2 <- 999
ed.frame$MAXVO2 <- round(ed.frame$MAXVO2, 2)

Error I recive:
Error: unexpected '{' in "If (18 <= ed.frame$Age && ed.frame$Age <= 99 && ed.frame$Sex == 1) {"

Any help/guidance is great appreciated.

The last brace } lacks an opening brace is the immediate cause. See the FAQ: How to do a minimal reproducible example reprex for beginners for future reference.

There are also easier ways to do operations based on logical tests


mtcars %>% filter(mpg > 20 & cyl == 4 & hp > 100)
#>               mpg cyl  disp  hp drat    wt qsec vs am gear carb
#> Lotus Europa 30.4   4  95.1 113 3.77 1.513 16.9  1  1    5    2
#> Volvo 142E   21.4   4 121.0 109 4.11 2.780 18.6  1  1    4    2

Created on 2021-02-20 by the reprex package (v1.0.0)

There are few problems with your code.

  1. The main error is If and Else. R is case sensitive, and it supports if and else only.
  2. Also, the expected format is the following, you can't start else in a new line.
if (condition1) { 
} else if (condition2) {
} else if  (condition3) {
} else {
  1. I think ed.frame is a data frame for you, and usually that has more than one rows. If that is the case, the result is not going to be what you expect. This is because if checks using first element only. You'd need a for loop to check for each row.

As Richard suggests above, there are alternative ways to do what you want, with or without external libraries. Those will certainly be better than a combination of for loop and if else. But this is such a basic thing in R that in my opinion, you should know these things well first before going on to those.

Hope this helps.

1 Like

Thank you. I will certainly look into your suggestions. About last brace lacks opening brace, I though I had in this statement: Else **{**ed.frame$MAXVO2 <- 999

Thank you

That's a great point. Yes, ed.frame is my data frame and has many rows. No wonder when I tried using mutate, the error was something like the code applies to only 1 record but data set has 1500+ rows. I definitely look into Richard's suggesiotn.

Thank you,