自定义函数上的 purrr::map 中的列名匹配

Vai*_*ngh 1 r dplyr purrr tidyverse

(使用虹膜可重现性)

我相信我的问题的措辞可以改进,但这是一个非常简单的问题,我需要返回n_distinct即 3 ifcolumn_name=="Species"和 mean if 其他人。另一部分效果很好,但我在 Species 列中收到 NA 作为输出,任何帮助我做错了什么。

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)
Run Code Online (Sandbox Code Playgroud)

Ron*_*hah 5

map无权访问列名,请imap改用。

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
Run Code Online (Sandbox Code Playgroud)