Skip to content

Instantly share code, notes, and snippets.

@dill
Last active April 15, 2020 22:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dill/9d686cf79e08f9162025 to your computer and use it in GitHub Desktop.
Save dill/9d686cf79e08f9162025 to your computer and use it in GitHub Desktop.
Make JSON for @RverbR
## This is a very silly script to get JSON data for an R twitter bot that produces
## tweets of the form "verb that noun" using verbs from package:base and nouns from
## built in R data.
##
## It uses @v21's http://cheapbotsdonequick.com/
##
## David L. Miller 2015 MIT license
## update from Nick Golding 2018
cat("{\n")
# get actual functions, thanks Nick!
object_names <- ls("package:base")
is_function <- function (name) is.function(get(name))
functions <- vapply(object_names, is_function, FALSE)
# print all the function names
cat("\"verb\":[\n")
cat(paste(paste0("\"", object_names[functions],
"\""), collapse=", \n "))
cat("],")
# print all the data types
# taken from ?typeof
types <- c("logical", "integer", "double", "complex",
"character", "raw", "list", "NULL", "closure",
"special", "builtin", "environment", "S4", "symbol",
"pairlist", "promise", "language", "char", "...",
"any", "expression", "externalptr", "bytecode",
"weakref")
cat("\"noun\":[\n")
cat(paste(paste0("\"",types,"\""),collapse=",\n "))
cat("],\n\n")
# template
cat("\"origin\": [\"#verb# that #noun#\"]\n")
# done!
cat("}\n")
@goldingn
Copy link

This currently lists all the objects in base, not just functions. So the following objects get tweeted as if they were functions:

c("F", "letters", "LETTERS", "month.abb", "month.name", "pi", "R.version", "R.version.string", "T", "version")

This is unacceptable.

The following will return only function names:

object_names <- ls("package:base")
is_function <- function (name) is.function(get(name))
functions <- vapply(object_names, is_function, FALSE)
object_names[functions]

so that line 13 becomes:

cat(paste(paste0("\"",object_names[functions],"\""),collapse=",\n "))

Yes, I really have nothing better to do.

@lashlee
Copy link

lashlee commented Apr 15, 2020

Just to throw in my two cents, I like the Filter function and find it a great way to accomplish that vapply-then-index pattern in one clear function call.

So instead of functions <- vapply(object_names, is_function, FALSE) then invoking object_names[functions], you could do functions <- Filter(is_function, object_names) and then invoke functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment