mercredi 28 avril 2021

How to use ifelse inside map function in R

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?

Aucun commentaire:

Enregistrer un commentaire