R程序中是否有类似MVC的结构可以同时更改多个脚本

时间:2015-07-07 18:07:43

标签: r rstudio

我在RStudio工作,我有一定数量的脚本,对应于我们网络所在的每个区域。

每次我对script1进行更新时,我都必须更新scripts2到script24。

这些脚本之间只有差异

  1. 工作目录
  2. .csv文件,读入数据框
  3. bbox周围的填充,即f值
  4. 以下是其中一个的实际代码

    library(ggmap)
    library(ggplot2)
    
    setwd("d:/GIS/different_directory")
    sep <- read.csv("district_number_SEP_assets_csv.csv")
    Sub1 <- sep[grep("SEP.12", names(sep))]
    sep$newCol <- 100*rowSums(Sub1)/rowSums(sep[4:7])
    
    
    # create a new grouping variable
    Percent_SEP12_Assets <- ifelse(sep[,8] <= 33, "Lower Third", ifelse(sep[,8] >= 66, "Upper Third", "Middle Third"))
    Percent_SEP12_Assets <- factor(Percent_SEP12_Assets,
                                   levels = c("Upper Third", "Middle Third", "Lower Third"))
    
    
    # get the map
    bbox <- make_bbox(sep$Longitude, sep$Latitude, f = varies from scripts)
    map <- get_map(bbox)
    
    
    # plot the map and use the grouping variable for the fill inside the aes
    ggmap(map) +
      geom_point(data=sep, aes(x = Longitude, y = Latitude, color=Percent_SEP12_Assets ), size=5, alpha=0.6) +
      scale_color_manual(values=c("green","orange","red"))
    

    必须有一种更简化的方法来实现这一目标。

    更多信息

    我根据数据点是否被切断来确定f,并尽可能保持f最低数量。

    script1中的更改​​对script2等没有影响。脚本是每个区域的副本,这样如果我更改script1,我必须更改script2。

    区号被硬编码到文件名中,并硬编码到R脚本中。

1 个答案:

答案 0 :(得分:1)

复制&amp;将所有csv粘贴到一个名为mywd

的文件夹中
#Then make this folder with all files your WD
setwd("d:/GIS/mywd")

# As you correctly noted, writing code the number of times you need to 
# run it is not much fun :-)
# `for` loops exist just for this. You write the code only once
# The `loop` then applies that code to as many inputs as you have
# in your case, district CSV's

创建所有分区csv文件的列表

dlist&lt; - list.files(“mywd”,pattern =“SEP_assets_csv.csv”)

使用for loop

在dlist中的csv文件列表中重复代码
for(sep in dlist){

sep <- read.csv("sep")
Sub1 <- sep[grep("SEP.12", names(sep))]
sep$newCol <- 100*rowSums(Sub1)/rowSums(sep[4:7])

# create a new grouping variable
Percent_SEP12_Assets <- ifelse(sep[,8] <= 33, "Lower Third", ifelse(sep[,8] >= 66, "Upper Third", "Middle Third"))
Percent_SEP12_Assets <- factor(Percent_SEP12_Assets,
                      levels = c("Upper Third", "Middle Third", "Lower Third"))

# get the map
# Note Exclusion of the `f` argument
# Data points are cut off because x, y or Percent_SEP12_Assets are missing
# You MUST have x and y coords to show any point, so any row without x or y must be excluded since its position is not fully described
# If `Percent_SEP12_Assets` is missing, we can show it with a special colour e.g. yellow

bbox <- make_bbox(sep$Longitude, sep$Latitude)
map <- get_map(bbox)

# plot the map and use the grouping variable for the fill inside the aes
(ggmap(map) + 
geom_point(data=sep, aes(x = Longitude, y = Latitude, 
  color=Percent_SEP12_Assets, size=5, alpha=0.6) +
  scale_color_manual(values=c("green","orange","red"), na.value="yellow"))
}

还有两件事,请参阅thisthis