Stat.Enthus
Stat.Enthus

Reputation: 335

Specify a row on mutate

I have this code which adds a different text for each line in the df.

mt<- mtcars %>% group_by(cyl,am) %>% nest() %>% 
  mutate(formula = "Add separate model for each row in text like mpg~wt for one row, mpg~wt+hp for another etc.")

mt$formula[[1]] <- "mpg~wt"
mt$formula[[2]] <- "mpg~wt+drat"
mt$formula[[3]] <- "mpg~wt+qsec"
mt$formula[[4]] <- "mpg~wt+gear"
mt$formula[[5]] <- "mpg~wt"
mt$formula[[6]] <- "mpg~wt+qsec"

Is there a more elegant way of referring to row number 1, like specifying cyl==6 and am==1 instead of the line number?

Thanks

Upvotes: 0

Views: 45

Answers (1)

stefan
stefan

Reputation: 123903

One option would be to use dplyr::case_when:

library(tidyr)
library(dplyr)

mt<- mtcars %>% group_by(cyl,am) %>% nest()

mt %>% 
  mutate(formula = case_when(
    cyl == 6 & am == 1 ~ "mpg~wt",
    cyl == 8 & am == 0 ~ "mpg~wt+drat"
  ))
#> # A tibble: 6 x 4
#> # Groups:   cyl, am [6]
#>     cyl    am data              formula    
#>   <dbl> <dbl> <list>            <chr>      
#> 1     6     1 <tibble [3 x 9]>  mpg~wt     
#> 2     4     1 <tibble [8 x 9]>  <NA>       
#> 3     6     0 <tibble [4 x 9]>  <NA>       
#> 4     8     0 <tibble [12 x 9]> mpg~wt+drat
#> 5     4     0 <tibble [3 x 9]>  <NA>       
#> 6     8     1 <tibble [2 x 9]>  <NA>

Upvotes: 2

Related Questions