Using glue to create a dynamic IP address for multiple sites, within a function R

87 Views Asked by At

I am trying to avoid a whole lot of repeating myself (copy/pasting) by using functions in my R code. I have a working function as per below, but I can't figure out how to build the IP/file path address inside the function for different sites. My problem is how to glue the unique usernames at each site.

Hopefully it makes sense when you read the code below and comments within. Apologies for any confusion, I'm finding it hard to explain as simply as possible

library(tidyverse)
library(data.table) 
library(lubridate)

#SiteA
siteip <- "10.10.10.10"
sitename <- "SiteA"
site <- "sitea"
PW <- "passwd" #same at all sites

# SiteB will need different variables to glue
# I've commented these out for ease of reading (turned text red as code was wrong)

# siteip <- 20.20.20.20
# sitename <- "SiteB     
# site <- "siteb"        
# PW <- "passwd" #same at all sites


# This months date format
Year <-format(Sys.Date(), format="%Y")
Month <- format(Sys.Date(), format="%B")
MM <- format(Sys.Date(), format="%m")

# Last months date format
LM <- format(Sys.Date() %m+% months(-1), format="%B")
Lmon <- format(Sys.Date() %m+% months(-1), format="%m")
LY <- format(Sys.Date() %m+% months(-1), format="%Y")

### Total GPS function

gps <- function(w,x,y,z) {
  w <- glue::glue("ftp://{sitename}:{PW}@{siteip}/1data/{site}/{LY}/{LM}/{site}}{LY}-{Lmon} GPS.txt") # last month data
  w <- fread(w, header = FALSE, select = c(1, 3, 4),
             col.names = c("DateTime", "Latitude", "Longitude"), sep = " ")
  x <- glue::glue("ftp://{sitename}:{PW}@{siteip}/1data/{site}/{Year}/{Month}/{site}}{Year}-{MM} GPS.txt") # This month data
  x <- fread(x, header = FALSE, select = c(1, 3, 4),
                  col.names = c("DateTime", "Latitude", "Longitude"), sep = " ")
  y <- unique(rbindlist(list(w, x))) # combine last month/this month
  z <- y %>%
    filter(between(as_datetime(DateTime), Sys.Date() - 10, Sys.Date())) # filter for last ten day's of data
}

siteagps <- gps(siteagps)
# works up to here

sitebgps <- gps(sitebgps)
# can't get this working
0

There are 0 best solutions below