下标作业4

时间:2018-10-15 09:50:06

标签: r iteration na

鉴于它们的重叠和相似的威胁过程,我正在尝试找到最具成本效益的物种进行管理(数据在https://drive.google.com/open?id=1caE6_WDObPQtzgE-hReOiKWYMO2JUgu5)。我有以下代码:

species_int <- subset(species_int, sp_a != sp_b)
species_int <- species_int %>% group_by(sp_a,sp_b) %>% summarise(
  n=n(),
  b_area = sum(unique(KM2_sp_b)),
  isect_area = sum(unique(Overlap_km)),
  prop_overlap = isect_area/b_area 
)        
U <- matrix(1,nrow=nrow(threats_species_matrix),ncol=nrow(Cost_threat_management))
    species_benefits <- function(){
      rs <- data.frame(species_id = threats_species_matrix$species_id, B = NA, C = NA)
      for (i in 1:nrow(rs)){
        overlaps <- subset(species_int,sp_a == threats_species_matrix$species_id[i])
        Tik = as.numeric(threats_species_matrix[i,5:46]) 
        Uik = U[i,]
        if (nrow(overlaps)==0){
          cat("No overlaps found for species ", i, ", ",threats_species_matrix$species_id[i], "\n")
          # cat("Setting benefit to zero \n")
          rs[i,"B"] =  threats_species_matrix$weight[i] * sum(Tik * Uik) / sum(Tik)
          rs[i,"C"] = sum(Tik * Cost_threat_management$Cost_m_year) * subset(area,ALL_MAPP_2==threats_species_matrix$species_id[i])$KM2[1]
          next
        }
        mtch <- match(overlaps$sp_b,threats_species_matrix$species_id) 
        overlaps$W <- threats_species_matrix$weight[mtch] 
        Tjk = as.matrix(threats_species_matrix[mtch,5:46]) 
        overlaps$total_threats <- apply(Tjk,1,sum)
        Ujk = U[mtch,]
        overlaps$common_threats <- as.numeric((Ujk*Tjk) %*% Tik) 
        overlaps$benefit_to_j <-  with(overlaps, prop_overlap * W * common_threats / total_threats)
        overlaps <- subset(overlaps,!is.na(W) & total_threats>0)
        rs[i,"B"] = sum(overlaps$benefit_to_j)
        rs[i,"C"] = sum(Tik * Uik * Cost_threat_management$Cost_m_year) * subset(area,ALL_MAPP_2==threats_species_matrix$species_id[i])$KM2[1]
        rs[i,"B"] =  rs[i,"B"] + threats_species_matrix$weight[i] * sum(Tik * Uik) / sum(Tik) 
      }
      rs$E = rs$B/rs$C
      return(rs)
    }
        benefits <- species_benefits()
        adjust_U <- function(U,species){
      i = which(threats_species_matrix$species_id == species)
      U[i,] <- 0 
      overlaps <- subset(species_int, sp_a == threats_species_matrix$species_id[i])
      mtch <- match(overlaps$sp_b,threats_species_matrix$species_id) 
      Tik = as.numeric(threats_species_matrix[i,5:46]) 
      U[mtch,] <- U[mtch,] * (1-outer(overlaps$prop_overlap,Tik,"*"))
      U[mtch] <- subset(U[mtch],is.na(1:42) >0)
      return(U)
    }

然后,我从每次运行中选择使用的前'E'种:

U <- adjust_U(U,"Acacia_pharangites")

我对70种动物反复进行此操作,但是,有时,我会收到错误消息: “在下标的作业中不允许使用NA”。

有什么方法可以将NA更改为0(如果它们出现在函数中)? 另外,还有一种更有效的方式来运行代码的最后一部分(即,从每次迭代中选择顶部的'E'种类并运行: U < / p>

谢谢

米歇尔

0 个答案:

没有答案