Rmarkdown - код работает нормально в скрипте, но когда knit выдает ошибку - PullRequest
0 голосов
/ 16 марта 2020

У меня есть один документ Rmarkdown, который был передан мне и прекрасно работал с человеком, который дал мне. Но когда я делаю свои данные, я не знаю, что происходит, когда я точно запускаю код с документом скрипта, но когда я пытаюсь связать его с html, выдается ошибка.

bhv_df <- plyr::ddply(bhv_df, ~segmentid, function(d){
  d= bhv_df[bhv_df$segmentid == bhv_df$segmentid[1], 
  # predictions are made based on the mid time between start and end of the message
  predObj <- crawl::crwPredict(object.crwFit = crawl_models_list[[d$segmentid[1]]], predTime = d$MidTime, speedEst=TRUE, flat=TRUE)
  predObj_dives <- predObj[predObj$locType == "p",]
  # reproject into lat/long, because the crawl models have been built in a mercator pacific centered CRS
  coord_points <- predObj_dives
  coordinates(coord_points) =~ mu.x + mu.y
  proj4string(coord_points) <- CRS("+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")
  predObj_dives[c("lon", "lat")] <- coordinates(spTransform(coord_points, CRS("+proj=longlat +datum=WGS84")))
  # calculate the lon360
  return(cbind(d, predObj_dives[c("mu.x", "mu.y", "lon", "lat")]))
})


#load("./Outputs/crawl_argos_df.RData")

######### MERGE DIVE DATASET with CRAWL-derived MOUVEMENT DATA
bhv_df <- plyr::ddply(bhv_df, ~segmentid, function(d){ # for each tag dive data
  cr <- crawl_argos_df[crawl_argos_df$segmentid == d$segmentid[1], ] # select the corresponding crawl track
  fl <- filtered_argos_df_crawl[filtered_argos_df_crawl$segmentid == d$segmentid[1], ] # select the corresponding filtered track
  d[c("lq_closest_filt","dt_closest_filt", "dist_closest_filt", "rel.angle","speed")] <- NA # add empty columns
  for (i in 1:nrow(d)){ # for each dive...
    fl$dist_diff <- as.vector(spDists(x = as.matrix(d[i,c("lon", "lat")]), y = as.matrix(fl[c("lon", "lat")]), longlat = T)) # distance calculated in km
    fl$dt_diff <- as.numeric(difftime(d$MidTime[i], fl$time, units = "hours"))
    d[i, "dt_closest_filt"] <- min(abs(fl$dt_diff)) # select the filtered position closest in time to the dive, time in hours
    d[i, "dist_closest_filt"] <- fl[which(abs(fl$dt_diff) == min(abs(fl$dt_diff))), "dist_diff"][1] # retrieve the distance from this filtered position to the dive location (predicted by crawl)
    d[i, "lq_closest_filt"] <- fl[which(abs(fl$dt_diff) == min(abs(fl$dt_diff))), "lq"][1] # argos quality of closest filtered argos position
    cr$diff <- as.numeric(difftime(d$MidTime[i], cr$time, units = "hours")) # look at the time diff between this dive and all positions recorded in crawl for that same tag
    d[i, c("rel.angle","speed")] <- cr[abs(cr$diff) == min(abs(cr$diff)), c("rel.angle", "speed")] # select closest position recorded when dive occurred
  }
  return(d)
})

bhv_df$depth_bin <- cut(bhv_df$DepthMean, seq(0, 700, 50))

ggplot(bhv_df[bhv_df$What == "Dive" & bhv_df$depth_range == "deep" & bhv_df$DepthMean < 1000,], aes(x = lon, y = lat)) +
  stat_contour(data = bathyNOAA_df, aes(x, y, z=z), binwidth = 500, color = "grey60", size = 0.2) +
  geom_tile(data = bathyNOAA_df_shallow[bathyNOAA_df_shallow$z >= 0, ], aes(x, y), fill = "grey10") +
  geom_jitter(aes(fill = -DepthMean, size = DepthMean), col="black", alpha=0.8, pch = 21, width=0.1) +
  scale_fill_viridis(option = "magma", name = "Dive Depth (m)", direction = 1, begin = 0.2) +
  xlab("Longitude") +
  ylab("Latitude") +
  coord_fixed(xlim = c(-50, -26), ylim = c(-55, -15), expand = F) 

Ошибка (это только в начале кода, в 4 строки):

Ошибка: неожиданный символ в: "predObj <- crawl :: crwPredict (object.crwFit = crawl_models_list [[ d $ segmentid <a href="https://i.stack.imgur.com/UaCKo.png" rel="nofollow noreferrer"> 1 ]], predTime = d $ MidTime, speedEst = TRUE, flat = TRUE) predObj_dives "

И это:

enter image description here

Я пытался выяснить, есть ли конфликты, но, по-видимому, нет

> conflicts()
 [1] "lines"         "cividis"       "inferno"       "magma"         "plasma"        "viridis"       "viridis.map"  
 [8] "summary"       "days"          "hours"         "minutes"       "origin"        "seconds"       "show"         
[15] "years"         "hour"          "isoweek"       "mday"          "minute"        "month"         "quarter"      
[22] "second"        "wday"          "week"          "yday"          "year"          "coerce"        "coerce"       
[29] "plot"          "show"          "summary"       "%>%"           "%>%"           "%>%"           "between"      
[36] "count"         "first"         "intersect"     "last"          "setdiff"       "union"         "%>%"          
[43] "flatten"       "map"           "transpose"     "%>%"           "add_row"       "as_data_frame" "as_tibble"    
[50] "data_frame"    "data_frame_"   "frame_data"    "glimpse"       "lst"           "lst_"          "tbl_sum"      
[57] "tibble"        "tribble"       "trunc_mat"     "type_sum"      "enexpr"        "enexprs"       "enquo"        
[64] "enquos"        "ensym"         "ensyms"        "expr"          "quo"           "quo_name"      "quos"         
[71] "sym"           "syms"          "vars"          "filter"        "lag"           "lines"         "plot"         
[78] "as.raster"     "data"          "Arith"         "coerce"        "Compare"       "initialize"    "show"         
[85] "as.difftime"   "body<-"        "date"          "intersect"     "kronecker"     "merge"         "Position"     
[92] "setdiff"       "setequal"      "split"         "subset"        "summary"       "union"        
> 

Кто-то знает, что происходит? Спасибо!

1 Ответ

0 голосов
/ 17 марта 2020

После многих попыток я удалил одну часть кода, и все заработало

# I removed: d= bhv_df[bhv_df$segmentid == bhv_df$segmentid[1], 

bhv_df <- plyr::ddply(bhv_df, ~segmentid, function(d){
  # predictions are made based on the mid time between start and end of the message
  predObj <- crawl::crwPredict(object.crwFit = crawl_models_list[[d$segmentid[1]]], predTime = d$MidTime, speedEst=TRUE, flat=TRUE)
  predObj_dives <- predObj[predObj$locType == "p",]
  # reproject into lat/long, because the crawl models have been built in a mercator pacific centered CRS
  coord_points <- predObj_dives
  coordinates(coord_points) =~ mu.x + mu.y
  proj4string(coord_points) <- CRS("+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs")
  predObj_dives[c("lon", "lat")] <- coordinates(spTransform(coord_points, CRS("+proj=longlat +datum=WGS84")))
  # calculate the lon360
  return(cbind(d, predObj_dives[c("mu.x", "mu.y", "lon", "lat")]))
})


######### MERGE DIVE DATASET with CRAWL-derived MOUVEMENT DATA
bhv_df <- plyr::ddply(bhv_df, ~segmentid, function(d){ # for each tag dive data
  cr <- crawl_argos_df[crawl_argos_df$segmentid == d$segmentid[1], ] # select the corresponding crawl track
  fl <- filtered_argos_df_crawl[filtered_argos_df_crawl$segmentid == d$segmentid[1], ] # select the corresponding filtered track
  d[c("lq_closest_filt","dt_closest_filt", "dist_closest_filt", "rel.angle","speed")] <- NA # add empty columns
  for (i in 1:nrow(d)){ # for each dive...
    fl$dist_diff <- as.vector(spDists(x = as.matrix(d[i,c("lon", "lat")]), y = as.matrix(fl[c("lon", "lat")]), longlat = T)) # distance calculated in km
    fl$dt_diff <- as.numeric(difftime(d$MidTime[i], fl$time, units = "hours"))
    d[i, "dt_closest_filt"] <- min(abs(fl$dt_diff)) # select the filtered position closest in time to the dive, time in hours
    d[i, "dist_closest_filt"] <- fl[which(abs(fl$dt_diff) == min(abs(fl$dt_diff))), "dist_diff"][1] # retrieve the distance from this filtered position to the dive location (predicted by crawl)
    d[i, "lq_closest_filt"] <- fl[which(abs(fl$dt_diff) == min(abs(fl$dt_diff))), "lq"][1] # argos quality of closest filtered argos position
    cr$diff <- as.numeric(difftime(d$MidTime[i], cr$time, units = "hours")) # look at the time diff between this dive and all positions recorded in crawl for that same tag
    d[i, c("rel.angle","speed")] <- cr[abs(cr$diff) == min(abs(cr$diff)), c("rel.angle", "speed")] # select closest position recorded when dive occurred
  }
  return(d)
}) #warnings probably due to RT being equal to NA at beginning and end of the track

Спасибо

...