Created
May 11, 2018 20:43
-
-
Save narath/c950282c6652f902c96f656c80053f69 to your computer and use it in GitHub Desktop.
R utility methods
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
# Collected R utility methods | |
read_all_csv_files <- function(dir) { | |
save_dir <- getwd() | |
setwd(dir) | |
files <- list.files(pattern = "csv") | |
for (file in files) { | |
if (!exists("dataset")){ | |
dataset <- read.csv(file) | |
} else { | |
temp_dataset <- read.csv(file, stringsAsFactors = FALSE) | |
dataset <- rbind(dataset, temp_dataset) | |
rm(temp_dataset) | |
} | |
} | |
setwd(save_dir) | |
return(dataset) | |
} | |
# convert datetimestamps | |
convert_date <- function(var) { | |
var <- as.character(var) | |
var[var == ""] <- NA | |
var <- as.POSIXct(var) | |
return(var) | |
} | |
# return the last item from a vector v, as identified by dates in vector dates | |
last_item <- function(v, dates) { | |
if (sum(!is.na(dates))==0) { return(NA) } | |
return(v[which(dates == max(dates, na.rm = TRUE))]) | |
} | |
# last_item(c("wrong","right","wrong"), as.POSIXct(c("2018-01-02","2018-12-31","2018-01-01"))) | |
# last_item(c("wrong","wrong"),c(NA, NA)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment