N. J.
N. J.

Reputation: 105

Turning a presence-absence matrix into a single variable per row in R

I have a presence absence matrix (comprised of 1s and 0s) for each individual ID. It is based on mark recapture data. Each column represents a sampling date. As a data frame, it looks like this (first 3 rows):

    ID        X X.1 X.2 X.3 X.4 X.5  Sex
    2014-001  0   0   1   0   1   0  F
    2014-002  0   0   1   1   0   0  M
    2014-003  0   1   0   0   1   1  F

I need an end product that looks like this:

        ch     Sex
    1   001010 F
    2   001100 M
    3   010011 F

Upvotes: 1

Views: 142

Answers (2)

tomasu
tomasu

Reputation: 1438

Here's a tidyverse solution as well:

library(tidyverse)

df <- read.table(
  h = T,
  text = "ID        X X.1 X.2 X.3 X.4 X.5  Sex
          2014-001  0   0   1   0   1   0  F
          2014-002  0   0   1   1   0   0  M
          2014-003  0   1   0   0   1   1  F"
)

df %>% 
  unite(ch, X:X.5, sep = "") %>% 
  select(-ID)
#>       ch Sex
#> 1 001010   F
#> 2 001100   M
#> 3 010011   F

Created on 2019-04-18 by the reprex package (v0.2.1)

Upvotes: 0

akrun
akrun

Reputation: 886938

We can use paste0 with do.call to paste the rows of the columns of interest and cbind with the last column

nm1 <- grep("^X(\\.\\d+)*", names(df1), value = TRUE)
cbind(ch = do.call(paste0, df1[nm1]), df1["Sex"])
#      ch Sex
#1 001010   F
#2 001100   M
#3 010011   F

Upvotes: 3

Related Questions