Last active
April 15, 2020 22:03
-
-
Save dill/9d686cf79e08f9162025 to your computer and use it in GitHub Desktop.
Make JSON for @RverbR
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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") |
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
This currently lists all the objects in base, not just functions. So the following objects get tweeted as if they were functions:
This is unacceptable.
The following will return only function names:
so that line 13 becomes:
Yes, I really have nothing better to do.