1

My data has 3 surveys per year (for 10 years) where 1 represents presence and 0s present absence. The subset looks like this

x <- structure(c(0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 
                 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 
                 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 
                 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1), 
               .Dim = c(4L, 3L, 4L))

I want to collapse these three columns into one in a way that every row that has 1 in any survey, shows 1 in the final otherwise shows 0.

Mikael Jagan
  • 9,012
  • 2
  • 17
  • 48
KimChiya
  • 31
  • 5
  • What do the dimensions of your array represent? ie, is it [subject, survey, year], or [year, survey, subject]…? – zephryl Feb 09 '22 at 12:41
  • 1
    Provide reproducible data `dput(mydata)`. Solution would something like `as.integer(rowSums(x)>0)` – zx8754 Feb 09 '22 at 13:14
  • @zephryl it is [site, survey, year] – KimChiya Feb 09 '22 at 14:01
  • 1
    Please have a look at the [*How to make a great R reproducible example*](https://stackoverflow.com/q/5963269/1655567) discussion in order to improve your question. – Konrad Feb 09 '22 at 14:32

2 Answers2

2

Collapse the second dimension of the array with apply:

apply(x, c(1L, 3L), function(y) as.integer(any(as.logical(y))))
##      [,1] [,2] [,3] [,4]
## [1,]    0    0    0    0
## [2,]    1    1    1    1
## [3,]    0    1    1    1
## [4,]    1    1    1    1

The result is a [site, year] matrix.

Mikael Jagan
  • 9,012
  • 2
  • 17
  • 48
1

We could use max

apply(x, c(1, 3), FUN = max)
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]    1    1    1    1
[3,]    0    1    1    1
[4,]    1    1    1    1
akrun
  • 874,273
  • 37
  • 540
  • 662