For循环功能循环了太多次

时间:2018-09-03 13:01:24

标签: r

我正在计算功能特征值的社区加权平均值(研究林业)。我必须将每种物种(树)的相对丰度乘以特征值。我有2个数据框,其中1个具有每个站点内每个物种的相对丰度,一个具有每个物种的平均特征值。我做了一个循环来自动执行计算,但是最终结果返回的是乘法的13倍而不是1倍(我有13个图,所以也许与此有关),因为我已经忙了好几天了我是R的新手,但是我必须要完成我的硕士学位。我想我今天已经达到逻辑思维的极限,无法找到我的错误:)有人可以帮我吗?我将在下面粘贴脚本:

加载数据,应用一些列名称,将NA填充为0

library(data.table)
traits <- read.csv("Trait value.csv", sep = ";")

plots_Maiz <- read.csv("CWM Maiz plot.csv", sep = ";")

plots_Maiz[is.na(plots_Maiz)] <- 0

colnames(plots_Maiz) <- c("site", "species","y0","y1", "y2", "y3", "y4",    "y5")

traits[,1:17][is.na(traits[,1:17])] <- 0

#function for finding the corresponding species for a plot in the traitlist



       traitsf <- function(df, traitlist){
plottraits <- subset(traitlist, species %in% df[,2])
return(plottraits)
}

traitcalc <- function(traits, plots_Maiz){

multlist <- list()
blist <- list()
vmult <- vector()
tickcount <- 0

plotsplit <- split.data.frame(plots_Maiz, plots_Maiz$site)
testlist <- lapply(plotsplit, traitsf, traitlist = traits)


for (q in 1:length(plotsplit)){
df1 <- testlist[[q]]
df2 <- plotsplit[[q]]

plot <- as.character(plotsplit[[q]][1,1]) 


for (i in 1:nrow(df1)){

  v <- as.numeric(as.vector(t(df1[i,2:ncol(df1)]))) 

  species <- as.character(df1[i,1]) 


  for (j in 1:(ncol(df2)-2)){

    tickcount <- tickcount + 1
    vmult <-as.vector(v * (as.numeric(as.vector(df2[i,j+2])))) 

    vmult <- as.list(c(vmult, j-1, species, plot)) 


    multlist[[tickcount]] <- vmult 

  }  
}

b <- do.call(rbind, multlist) 
b <- data.table::rbindlist(multlist)


blist[[q]] <- b 

}

return(blist)
}

endresults <- traitcalc(traits,plots_Maiz) 
endresultsdf2<- do.call("rbind", endresults)

0 个答案:

没有答案