knitr::opts_chunk$set(echo = TRUE)

library(dplyr)

Un problème

Est-ce qu'il y a un moyen d'écrire la fonction sum_is_null auquel le code ci-dessous fait allusion?

d <- tibble::tibble(
  x = 1:3,
  y = list(NULL, NA, Inf),
  z = list(NULL, NULL, 0)
)
dplyr::summarise_all(
  d, ~ sum_is_null # is that doable?
)
# desired output:
# x y z
# 0 1 2

Les données

d <- tibble::tibble(
  x = 1:3,
  y = list(NULL, NA, Inf),
  z = list(NULL, NULL, 0)
)

Solution 1

sum_is_null <- function(x) 
  sum(sapply(x, is.null))

dplyr::summarise_all(d, sum_is_null)

Solution 2

sum_is_null <- function(x) 
  sum(lengths(x) < 1)

dplyr::summarise_all(d, list(sum_is_null))


jimtyhurst/codesamplerr documentation built on Aug. 13, 2021, 8:45 a.m.