Skip to content

Instantly share code, notes, and snippets.

@strboul
Created May 12, 2018 20:44
Show Gist options
  • Save strboul/892c685f3317c9a9ff5ee6e01766dc33 to your computer and use it in GitHub Desktop.
Save strboul/892c685f3317c9a9ff5ee6e01766dc33 to your computer and use it in GitHub Desktop.
############################################################
#### Anonymous functions in R ####
############################################################
capitals <- c("Amsterdam", "Paris", "Warszawa", "Istanbul")
lapply(capitals, function(name) nchar(name))
# function with no name assigned to it, and does not appear in global env.:
{function(x) x^2}(5)
(function(x) x^2)(4) # without curly brackets
# draw a plot (kinda it is in a loop):
plot(function(x) x^2)
# directly assign value from function:
a <- {function (x,y) x^y} (2,3)
# 'a' returns 8!
a
# In a for loop (obviously not very useful):
L <- list()
for (i in 1:5) {
L[[i]] <- {function(x) x^2}(i)
}
test <- local({
function(x) x^2
})
test(5)
##
square_add <- function(x) {
sq <- x ^ 2
if (x > 4) {
function(x) {
log(x)
}
}
sq
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment