简体   繁体   中英

How to use ~ function notation using apply-family functions in R?

Is there a way to use the "~." function notation with apply/lapply functions in R?

As a very simple example, I'd like to do the second of the two applies, to add "_se" to each of a list of strings:

cols <- c("x1", "x2")
sapply(cols, function(x) paste0(x, "_se")) # works, is long

sapply(cols, ~paste0(., "_se")) # doesn't work, I want to save the typing

Is there a way to do something resembling the second solution? Any other substitutes people like?

We don't need a loop here as paste , paste0 etc. are all vectorized

paste0(cols, "_se")
#[1] "x1_se" "x2_se"

If we use ~ , make sure to use it with map as this works with tidyverse functions

library(purrr)
map_chr(cols, ~ paste0(.x, "_se"))
#[1] "x1_se" "x2_se"

Or another option is as_mapper

sapply(cols,  as_mapper(~ paste0(.x, "_se")))
#     x1      x2 
#"x1_se" "x2_se" 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM