How can I convert TRUE values in a matrix to specific values in R?

18 views Asked by At

I have banding data from 1960 until 2022 and want to run a mark recapture model through RMark on juveniles. I'm having some issues converting the banding records into encounter histories due to the size of the dataset >200k records.

My dataset contains band numbers (identifier), the year of the event and if the bird a seen alive or dead (Alive = B, Dead = E).

I found some code from another user that seems to work when encounter histories are just 1's and 0's for a given year, but have been unable to adapt it to my situation. The code I've tried to use is as follows.

The encounter histories have to be structured as follows. Seen alive but not dead = 10, banded alive then seen dead = 11, or not seen alive or dead = 00. Each year should contain one of these values. So, '10 00 00' would indicate it was banded in year one and not seen in year two or three.

(I used some made-up data to see how it would work prior to using on a larger dataset)

 `
    ID <- c(1, 2, 3, 4, 5, 2, 4, 5)
    year <- c(2021, 2021, 2021, 2021, 2021, 2022, 2022, 2022)
    oc <- c("B", "B", "B", "B", "B", "E", "E", "E")

    dt <- data.frame(ID, year, oc)


    band.list = as.character(unique(dt$ID)) # create a vector of bands
    yr.list = as.character(unique(dt$year)) # make a vector of the years

    enc.hist = as.data.frame(matrix(rep(NA,(length(band.list)*length(yr.list))),
                                length(band.list), length(yr.list)))

    colnames(enc.hist) = rec
    rownames(enc.hist) = band.list

    # fill in data frame using a for-loop:
    for (i in 1:length(yr.list))
    {
      sub <- dt[dt$year == yr.list[i],] #subset datos down to just the year I'm currently looping
      subtags <- unique(sub$ID) #creates vector of bands present in that year
      enc.hist[,i] <- band.list %in% subtags #fills in the column of enc.hist with True or False if that     
      band is seen or not
    }
    head(enc.hist) # you now have a matrix with TRUE (1)/FALSE (0) for encounters:

    ## Finally, use logical syntax to convert TRUE and FALSE
    enc.hist[enc.hist==TRUE & oc=="B"] <- 10
    enc.hist[enc.hist==TRUE & oc=="E"] <- 11
    enc.hist[enc.hist==FALSE] <- 00
    enc.hist
    `

The problem seems to be that the code is unable to convert the TRUE values from the matrix into the proper encounter history (10, 11)

If there is a way to modify this code to work my situation or another way that would work better that would be great.

0

There are 0 answers