Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mutate variable in main df from conditional in nested df

How can one create a new variable in the main dataframe using a conditional (if else) statement based on nested data in a list-column?

If we take the cars dataset:

library(dplyr)

cars_nest <- mtcars %>%
  group_by(cyl) %>%
  nest()

And want to create a binary variable where any value of carb > 2 equals 1, otherwise 0. I tried the following but get an error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

cars_nest  <- cars_nest |> 
  mutate(test = ifelse(any(cars_nest$carb) > 2, 1, 0))

>Solution :

A few problems in your code:

  1. Your any should include the condition (i.e. any(... > 2))
  2. You don’t have a cars_nest variable to use in mutate, that is the name of the dataframe object, not the column (it should be data column)
  3. You need rowwise for this type of operation

One suggestion:

  1. Since the output of a logical comparison (... > 2) is already logical, you can take advantage of as.integer to corce it into integers without using ifelse

So the code should be:

library(tidyverse)

cars_nest <- mtcars %>%
  group_by(cyl) %>%
  nest() 
  
cars_nest %>% 
  rowwise() %>% 
  mutate(test = as.integer(any(data$carb > 2)))
  # or mutate(test = ifelse(any(data$carb > 2), 1, 0))

# A tibble: 3 × 3
# Rowwise:  cyl
    cyl data                test
  <dbl> <list>             <dbl>
1     6 <tibble [7 × 10]>      1
2     4 <tibble [11 × 10]>     0
3     8 <tibble [14 × 10]>     1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading