How to use ifelse inside map function in R

Viewed 1223

I am having problems with this ifelse sentence inside map function:

df<-list(mtcars,mtcars)

All I want to do is to organize each dataframe of this list this way:slice(x,c(n(),2:(n()-1),1))

map(df, ~   slice(.x,c(n(),2:(n()-1),1)))   # it works well. 

But I cant do this inside ifelse when I set the condition x$cyl == 4:

map(df, ~   ifelse(sum(.x$cyl == 4) > 0, slice(.x,c(n(),2:(n()-1),1)), .x)) # The output is weird

I tried to do the same using lapply but its not working:

lapply(df, function(x) ifelse(sum(x$cyl == 4) > 0, slice(x,c(n(),2:(n()-1),1)),x))

Any help?

2 Answers

We can use map_if to apply the function only when a condition is TRUE.

library(tidyverse)

df <- list(mtcars,mtcars)

df2 <- map_if(df, .p = function(y) any(y$cyl == 4),
                  .f = ~slice(.x, c(n(), 2:(n()-1), 1)))

This approach checks each data.frame in the list for any rows where cyl == 4. If it meets that condition, your desired slice is returned. Otherwise, the data.frame is returned unchanged.

library(dplyr)


df<-list(mtcars,mtcars)



lapply(df, function(x) {
  if (any(x$cyl == 4)) {
    slice(x, c(n(), 2:(n()-1), 1)) 
    } else { 
      x 
    }
  })

If you strongly prefer map:

library(dplyr)
library(purrr)

df<-list(mtcars,mtcars)



map(df, ~ 
  if (any(.x$cyl == 4)) {
    slice(.x, c(n(), 2:(n()-1), 1)) 
    } else { 
      .x 
    }
  )
Related