我有一个非常大的数据集,我想将其绘制成传单,但是我使用的“ for循环”需要很长时间。有人告诉我使用mapply函数会更快,但是我不知道如何将for循环转换为mapply。
我的最终目的是使我的代码运行得更快。
看一下我的数据集和地图结果的例子:
#import libraries:
library(data.table)
library(leaflet)
#dataset:
lat<-c(40.41766, 40.43305 ,40.43687, 40.39563, 40.39088, 40.39215, 40.39458, 40.40451, 40.40627, 40.40864)
lng<-c(-3.701328, -3.709352, -3.708531, -3.736556, -3.734796, -3.741867, -3.741222, -3.705399, -3.710980, -3.710310)
colors<-c("#3D00FFFF","#52FF00FF","#3D00FFFF","#0052FFFF","#52FF00FF","#52FF00FF","#52FF00FF","#0052FFFF","#3D00FFFF","#0052FFFF")
name<-c("Rafa","Luis","Rafa","Belen","Luis","Luis","Luis","Belen","Rafa","Belen")
hour_range<-c("Sleeping_Hours","Morning_rush_hours","Morning_Working_Hours","Sleeping_Hours","Morning_rush_hours","Morning_Working_Hours","Sleeping_Hours","Morning_rush_hours","Morning_Working_Hours","Morning_Working_Hours")
data<- data.table(name,lat,lng,hour_range,colors)
#As you can see the data.table has 5 variables (name, lat, lng, hour_range,colors)
#My objective is to plot in leaflet a line of every person (name)in a
#different color and also with 1 layer for each hour_range).
#I was able to do so with a for loop:
map<- leaflet(data)
map<- addTiles(map)
for( name in unique(data$name)){
map<- addPolylines(map, lng=~lng,lat=~lat,data=data[data$name==name & data$hour_range=="Sleeping_Hours",], group= "Sleeping_Hours",color=~colors)
map<- addPolylines(map, lng=~lng,lat=~lat,data=data[data$name==name & data$hour_range=="Morning_rush_hours",], group= "Morning_rush_hours",color=~colors)
map<- addPolylines(map, lng=~lng,lat=~lat,data=data[data$name==name & data$hour_range=="Morning_Working_Hours",], group= "Morning_Working_Hours",color=~colors)
}
map<-addLayersControl(map=map,
overlayGroups=c("Sleeping_Hours","Morning_rush_hours","Morning_Working_Hours"),
options=layersControlOptions(collapsed=FALSE)
map
此地图可以正常工作,因为它是一个较小的数据集,但如果数据集较长,则不起作用,如何使它运行得更快?我如何在这里应用mapply函数而不是循环?
谢谢!