You can iterate over an index, but this is not very R-like code. A more direct route is to use Map
, the multivariate version of lapply
, which iterates a function of appropriate arity in parallel across whatever parameters are passed to it:
Map(function(value, name){paste(name, sum(value), sep = ": ")},
Formaldehyde,
names(Formaldehyde))
#> $carb
#> [1] "carb: 3.1"
#>
#> $optden
#> [1] "optden: 2.747"
If using the tidyverse, purrr::imap
is a similar convenience version of purrr::map2
that automatically uses the names of the first parameter as a second parameter:
purrr::imap(Formaldehyde, ~paste(.y, sum(.x), sep = ": "))
#> $carb
#> [1] "carb: 3.1"
#>
#> $optden
#> [1] "optden: 2.747"
Versions of each that simplify are available: for Map
, mapply
, a multivariate sapply
(of which Map
is technically just a wrapper with SIMPLIFY = FALSE
); for imap
, versions with a subscript of the type to simplify to, e.g. imap_chr
.