Heidi Waite
Heidi Waite

Reputation: 1

Create a new column with mutate but using different columns based on condition (if...else statement?)

Let’s say I have a few columns:

I want to calculate some metrics using these in a new column called “proportion.life.duration”. BUT how I calculate (which variables to use) depends on what life stage.

So if life stage == “adult” then I want it to calculate the value in the new “prop.life.duration” column as “length of exposure/ (life span - age at maturity)“.

But if juvenile, I want to calculate using "length of exposure / dtm"; if larvae, I want to calculate as "length of exposure / larval duration"

HOW DO I DO THAT? in R

I thought maybe if..else statements with mutate() but havent figured out how to do that with three levels (adult, juvenile, and larva) AND using different columns to calculate for each.

Upvotes: 0

Views: 51

Answers (1)

r2evans
r2evans

Reputation: 160607

Try this

library(dplyr)
mydata %>%
  mutate(
    proportion.life.duration = case_when(
      `life stage` == "adult"    ~ `length of exposure` / (`life span` - `age at maturity`),
      `life stage` == "juvenile" ~ `length of exposure` / dtm,
      `life stage` == "larvae"   ~ `length of exposure` / `larval duration`
    )
  )

The backticks around variable names are because the variable names I assume you have contain spaces. If your real column names do not have spaces, you don't need the backticks (as in dtm above).

Upvotes: 0

Related Questions