Skip to contents

This function apply a function over a list-like object preserving its attributes and simplify (if requested) the list as sapply function does. slapply returns a list of the same length as 'x', each element of which is the result of applying FUN to the corresponding element of 'x'.

Usage

slapply(
  x,
  FUN,
  keep.attr = FALSE,
  class = NULL,
  simplify = TRUE,
  USE.NAMES = TRUE,
  ...
)

Arguments

x

A list-like or vector-like object.

FUN, ...

The same as described in lapply.

keep.attr

Logic. If TRUE, then the original attributes from 'x' are preserved in the returned list. Default is FALSE.

class

Name of the class to which the returned list belongs to. Default is NULL.

simplify, USE.NAMES

The same as described in sapply.

Value

Same as in ?base::lapply if keep.attr = FALSE. Otherwise same values preserving original attributes from 'x'.

See also

Author

Robersy Sanchez (https://genomaths.com).

Examples

## Create a list
x <- list(a = seq(10), beta = exp(seq(-3, 3)), 
          logic = c(TRUE, FALSE, FALSE, TRUE))
class(x) <- "nice"

## To compute the list mean for each list element using 'base::lapply'
class(slapply(x, mean, simplify = FALSE))
#> [1] "list"

## Simply 'base::lapply' preserving attributes
slapply(x, mean, keep.attr = TRUE, simplify = FALSE)
#> $a
#> [1] 5.5
#> 
#> $beta
#> [1] 4.535125
#> 
#> $logic
#> [1] 0.5
#> 
#> attr(,"class")
#> [1] "nice"

## To preserve attributes and simplify
slapply(x, mean, keep.attr = TRUE, simplify = TRUE)
#>        a     beta    logic 
#> 5.500000 4.535125 0.500000 
#> attr(,"class")
#> [1] "nice"