Vaibhav Singh
Vaibhav Singh

Reputation: 1209

column name match in purrr::map on custom function

(Using iris for reproducibility)

I believe wording of my questions can be improved but its a really simple problem, I need to return n_distinct i.e. 3 if column_name=="Species" and mean if others. The other part works good but I receive NA as output in Species column, any help what I am doing wrong.

library(tidyverse)

new_mean <- function(col_name) {
if(col_name=="Species")
{
  return(n_distinct(col_name))
}
else
{
  return(mean(col_name))
}  
}

purrr::map_dfr(iris,new_mean)

Upvotes: 1

Views: 292

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

map does not have access to column names use imap instead.

new_mean <- function(value, col_name) {
  if(col_name=="Species")
    return(dplyr::n_distinct(value))
  else
    return(mean(value))
}
purrr::imap_dfr(iris,new_mean)

#  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#         <dbl>       <dbl>        <dbl>       <dbl>   <int>
#1         5.84        3.06         3.76        1.20       3

Upvotes: 5

Related Questions