Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Mutate with apply statement in dplyr chain

$
0
0

Let's say I want to get a count of the variables that are greater than 5 in the iris dataset for each row:

iris %>%
  mutate(n_greater=apply(.,1,function(x) length(x[(x>5)])),
         n_less=apply(.,1,function(x) length(x[(x<5)])))  ##Is incorrectly counting factor column

iris %>% select_if(is.numeric) %>%
  mutate(n_greater=apply(.,1,function(x) length(x[(x>5)])),
         n_less=apply(.,1,function(x) length(x[(x<5)]))) ##Correct, but I need the non-numeric columns (species) in the end

iris %>%
  mutate_if(is.numeric,n_greater=apply(.,1,function(x) length(x[(x>5)]))) ##Does not work

Note, I have also tried incorporating which logic into the custom function call to no success. I can do this, but would like a dplyr solution.

n_greater=apply(iris[,-1],1,function(x) length(x[(x>5)]))
n_less=apply(iris[,-1],1,function(x) length(x[(x<5)]))
final_iris=cbind(iris,n_greater,n_less) #This is it

Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>