1
votes

I am very new to R and coding in general.

I would like to create a new variable in the mtcars dataframe called "x". If the transmission is automatic, then taken the sum of mpg and disp. If the transmission is manual, then take the sum of mpg and cyl.

How would I do this? Thank you!

1
mtcars$x <- mtcars$mpg + ifelse(mtcars$a == 0, disp, cyl) - r2evans
Have you tried anything so far? Even though it's a pretty straightforward problem, it might be helpful to see where you've gotten - camille
transform(mtcars, x = mpg + ifelse(am==0, disp, cyl)) - r2evans

1 Answers

2
votes

One way to do it is with dplyr::mutate() and dplyr::if_else(). Like this:

library(dplyr)

mtcars %>% 
  mutate(x = if_else(
    am == 0,
    mpg + disp,
    mpg + cyl
  ))

Or a base R solution, with no need to install additional packages:

mtcars$x <- 
  ifelse(mtcars$am == 0,
         mtcars$mpg + mtcars$disp,
         mtcars$mpg + mtcars$cyl
         )
mtcars