Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中随时间保持排名_R_Time Series_Rank - Fatal编程技术网

在R中随时间保持排名

在R中随时间保持排名,r,time-series,rank,R,Time Series,Rank,在R中是否有一种方法可以检查等级是否随着时间的推移而保留以供个人观察? 多年来,我测量了许多植物,希望检查大型植物是否保持大型,小型植物是否保持小型(即大型植物是否阻止其他植物生长)。这些植物的大小(从小到大)排在1-5位。 我测量了大约1000株植物 非常感谢您的回答或评论。 /斯蒂娜也许你会这样做 # create random data plantId <- sample(1:50,1000,replace=TRUE) rank <- sample(1:5,1000,re

在R中是否有一种方法可以检查等级是否随着时间的推移而保留以供个人观察? 多年来,我测量了许多植物,希望检查大型植物是否保持大型,小型植物是否保持小型(即大型植物是否阻止其他植物生长)。这些植物的大小(从小到大)排在1-5位。 我测量了大约1000株植物

非常感谢您的回答或评论。
/斯蒂娜

也许你会这样做

# create random data
plantId <- sample(1:50,1000,replace=TRUE)
rank    <- sample(1:5,1000,replace=TRUE)
time    <- as.POSIXct(sample(1000000:10000000,1000,replace=FALSE)+10000000*rank,origin="1970-01-01")
myData <- data.frame(plantId , rank, time )

# function to calculate the time a plant has a given rank
getRankTime <- function(id,testRank,data=myData){
  plantData <- myData[myData$plantId==id,];
  if(nrow(plantData) < 2){ # only one observed value of this plant
    return(NA)
  }else if(all(plantData$rank != testRank)){ # plant was never of the rank under consideration
    return(NA)   
  }else{ # calculate the (censered) time the plant stay(ed) in rank 'testRank'
    startObsTimeInRank <- min(plantData$time[plantData$rank == testRank])
    if(any(plantData$rank > testRank)){
      endObsTimeInRank <- min(plantData$time[plantData$rank > testRank])
    }else{
      #eighter take the last time
      endObsTimeInRank <- max(plantData$time[plantData$rank == testRank])  
      # alternatively use the current time
      # endObsTimeInRank <- Sys.time()
    }
    return(as.numeric(endObsTimeInRank - startObsTimeInRank))
  }
}

# calculate the average time plants stay in a rank
allPlantIds <- unique(myData$plantId)
stayInRankTime <- list()
for(runRank in 1:5){
  stayInRankTime[[runRank]] <- sapply(allPlantIds, function(runPlatId) getRankTime(runPlatId,runRank) )
}
# average time plants stay in acertain rank'
avgRankTime <- lapply(stayInRankTime,function(x)mean(x, na.rm =TRUE))
avgRankTime
#创建随机数据
植物