Last active
August 20, 2016 17:11
-
-
Save mkearney/7474b64f9db177435de540f5fa63a087 to your computer and use it in GitHub Desktop.
rtweet save_as_csv function(s)
This file contains 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 function is now included in the development version | |
## of rtweets. install instructions can be found on the | |
## package readme (or my github rtweet repo) | |
## Read in the following functions | |
save_as_csv <- function(x, file_name) { | |
if (missing(file_name)) { | |
stop("must provide file_name.", call. = FALSE) | |
} | |
if (all(c("tweets", "users") %in% names(x))) { | |
write_as_csv(x$tweets, | |
modify_file_name(file_name, "tweets")) | |
write_as_csv(x$users, | |
modify_file_name(file_name, "users")) | |
} else { | |
write_as_csv(x, modify_file_name(file_name)) | |
} | |
} | |
modify_file_name <- function(file_name, ext = NULL) { | |
stopifnot(is.character(file_name), length(file_name) == 1) | |
file_name <- gsub(".csv", "", file_name) | |
if (is.null(ext)) { | |
file_name <- paste0(file_name, ".csv") | |
} else { | |
file_name <- paste0(file_name, ".", ext, ".csv") | |
} | |
file_name | |
} | |
write_as_csv <- function(x, file_name) { | |
stopifnot(is.data.frame(x)) | |
x[is_list(x)] <- lapply(x[is_list(x)], collapse_list) | |
write.csv(x, file_name, row.names = FALSE) | |
} | |
collapse_list <- function(x) { | |
vapply(x, function(x) paste(x, collapse = " "), | |
FUN.VALUE = vector("character", 1)) | |
} | |
is_list <- function(x) { | |
vapply(x, is.list, FUN.VALUE = vector("logical", 1)) | |
} | |
## load rtweet package | |
library(rtweet) | |
## gather tweets | |
o <- search_tweets("olympics", n = 300) | |
## save tweets AND users data frame as CSV | |
save_as_csv(o, "olympics") | |
## should have two objects saved: | |
## olympics.tweets.csv | |
## olympics.users.csv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment