我在RStudio工作,我有一定数量的脚本,对应于我们网络所在的每个区域。
每次我对script1进行更新时,我都必须更新scripts2到script24。
这些脚本之间只有差异
以下是其中一个的实际代码
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脚本中。
答案 0 :(得分:1)
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
dlist&lt; - list.files(“mywd”,pattern =“SEP_assets_csv.csv”)
for loop
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"))
}