首页 > 解决方案 > 在函数 R 中使用胶水为多个站点创建动态 IP 地址

问题描述

我试图通过在我的 R 代码中使用函数来避免大量重复自己(复制/粘贴)。我有一个如下的工作函数,但我不知道如何在函数内为不同的站点构建 IP/文件路径地址。我的问题是如何在每个站点上粘贴唯一的用户名。

希望当您阅读下面的代码和其中的注释时它是有意义的。对任何混淆表示歉意,我发现很难尽可能简单地解释

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

标签: rfunctionr-glue

解决方案


推荐阅读