1

I would like to create a new variable based on an if/else statement. Pretty much I need to run a calculation for a new variable, but the calculation is different for men vs women. I know how to write the code using mutate to get a new column using the calculation, but am having a hard time creating a conditional statement based on sex. Here is what I have so far:

This is just applying the calculation to men and women:

test2 <- mutate(test, FEV1 = 443 - (30*Age) + (23*Height))

This is what I would like to do (I know it's not correct)

test2 <- mutate(test, FEV1 = ifelse( Sex ==1, *equation1*, *equation2*))

Thanks in advance for any help!

user7777508
  • 101
  • 1
  • 3
  • 9
  • There exist several options, but keep it simple. Add two extra columns: one holds the conditions of men, the other column for female. Next step, add a "final" result column that preserves the result based on a simple ifelse. IFELSE( Sex ==M, column_men, column_female) – OB83 Mar 28 '17 at 08:11

1 Answers1

1

I'm not sure what is the problem, but you are almost there. How about:

library("dplyr")    
df <- data.frame(sex = c("M", "F", "M", "F"))
df$test2 <- mutate(df, var = ifelse(sex == "M", runif(1), 2))

You could do it as well directly (without using mutate).

df$test3 <- ifelse( df$sex == "M", runif(1), 2)  
Edgar Santos
  • 3,426
  • 2
  • 17
  • 29