0

Let’s say I have a few columns:

  • life stage (levels: adult, juvenile, larva)
  • Length of exposure (numeric)
  • life span (numeric)
  • age at maturity (numeric)
  • larval duration (numeric)
  • dtm (numeric)

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.

  • 3
    Can you provide a small subset of your data as example to generate the results you are looking for? – S-SHAAF Feb 12 '23 at 22:40
  • 5
    Does this answer your question? [Can dplyr package be used for conditional mutating?](https://stackoverflow.com/questions/24459752/can-dplyr-package-be-used-for-conditional-mutating) Especially the `case_when` example in accepted answer. For More `case_when` details and examples you can also check `?case_when` or https://dplyr.tidyverse.org/reference/case_when.html#ref-examples – margusl Feb 12 '23 at 22:43

1 Answers1

0

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).

r2evans
  • 141,215
  • 6
  • 77
  • 149