r - Binning dates into decades, by column, in a matrix -
i have simulated matrix of dates generated probability function. each column represents single iteration.
i bin each run separately decades , dump them new matrix each column length of decades single run number dates binned decade.
i have done single vector of dates, not matrix:
"dates" vector of observed data representing when trees established in population
#find min , max decade mindecade <- min(dates) maxdecade <- max(dates) #create vector of decades alldecades <- seq(mindecade, 2001, by=10) #make empty vector of same length decade vector bin.vec <- rep(0,length(alldecades)) #populate bin.vec (empty vector) number of trees in each decade (i in 1:length(alldecades)) { bin.vec[i] <- length(which(dates==alldecades[i])) }
bin.vec:
0 0 0 0 0 0 0 0 0 0 1 1 1 0 1 2 0 1 3 0 1 3 8 5 9 8 5 5 4 10 3 6 9 17 32 37 35 25 31 41 41 44 45 40 50 43 59 42 46 28 16 18 20 16 11 4 7 1
this need do, each separate column in matrix.
my matrix looks (it has 835 rows, used head()
shorten it):
1 2 3 4 5 1 1891 1791 1771 1741 1981 2 1881 1851 1941 1831 1841 3 1981 1861 1761 1781 1791 4 1911 1901 1941 1801 1801 5 1771 1751 1841 1751 1951 6 1821 1871 1821 1691 1851 7 1851 1851 1931 1921 1931 8 1921 1941 1601 1751 1861 9 1741 1761 1931 1791 1891 10 1751 1891 1951 1931 1901
each column separate iteration of simulation (runs <- 10
) . how can bin each column decades separately?
i answered on r-help morning, although data offered looked transpose of data give here:
> dates <- scan() 1: 1891 1791 1771 1741 1981 6: 1881 1851 1941 1831 1841 11: 1981 1861 1761 1781 1791 16: 1911 1901 1941 1801 1801 21: 1771 1751 1841 1751 1951 26: 1821 1871 1821 1691 1851 31: 1851 1851 1931 1921 1931 36: 1921 1941 1601 1751 1861 41: 1741 1761 1931 1791 1891 46: 1751 1891 1951 1931 1901 51: read 50 items dates <- matrix(dates, ncol=5, byrow=true) apply( dates, 2, function(colm){ 1 + max(findinterval(colm, alldecades)) - min(findinterval(colm, alldecades) ) } ) #----------- #[1] 25 20 36 25 20
in answer did note problem description ambiguous . if want matrix number of rows equal length of 'alldecades' use code:
apply( dates, 2, function(colm) { alldec0 <- rep(0, length(alldecades)) names(alldec0) <- 1:length(alldec0) alldec0[ as.numeric(names(table(findinterval(colm, alldecades))))] <- table(findinterval(colm, alldecades)) return(alldec0) } )
Comments
Post a Comment