Search code examples
rfor-loopsapply

Use if statement in apply to create new variable


I have a data.frame with ID number, Sex and age. I want to create column with a score based on sex and age. First I want to assign a score of 1 to all males, M

ID   Sex   Age   sex_score
1    M     72    1
2    M     65    1
3    F     55    0

I have tried with both a for loop and with sapply but I'm still a beginner and don't really know how to use these. These are my attempts:

sex_score <- for (i in 1:nrow(df)) {if (df$Sex == "M") {1} else {0}} I get the warnings

In if (eligible$Sex == "M") {... :
the condition has length > 1 and only the first element will be used 

I've also tried Sex_score <- sapply(df,function(x)if (df$Sex == "M") {1} else {0}) I get the same warnings.


Solution

  • I advise you to use package tidyverse. If your data.frame is named df (please don't name your data.frame data.frame) try:

    df %>%
      mutate(sex_score = as.integer(Sex == "M"))