Skip to content

Instantly share code, notes, and snippets.

@shravan-kuchkula
shravan-kuchkula / forLoopInR.R
Created March 31, 2017 18:16
A safer way to write a for loop in R. Use seq_along() to handle an empty data frame. Useful when using a for loop within a function.
df <- data.frame(
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
# Replace the 1:ncol(df) sequence
for (i in seq_along(df)) {
print(median(df[[i]]))
@shravan-kuchkula
shravan-kuchkula / installRequiredPackages.R
Created March 31, 2017 08:54
Install and load packages in R
# Install a package and load it.
installRequiredPackages <- function(pkg){
new.pkg <- pkg[!(pkg %in% installed.packages()[,"Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}
libs <- c("readr", "dplyr", "tidyr", "ggplot2",
"magrittr", "markdown", "knitr", "Hmisc",
@shravan-kuchkula
shravan-kuchkula / generateWordCloud.R
Last active March 31, 2017 08:57
Create a word cloud from a list of tweets.
# Takes a list of status/twitter objects, extracts the text,
# cleans the text, calculates word frequencies and generates
# a word cloud.
generateWordCloud <- function(tweets){
#Get the text from the status/twitter object
tweets_list <- sapply(tweets, function(x) x$getText())
#Remove any weird symbols from the text
tweets_list <- str_replace_all(tweets_list, "[^[:graph:]]", " ")