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.

4
  • What do the dimensions of your array represent? ie, is it [subject, survey, year], or [year, survey, subject]…? Commented Feb 9, 2022 at 12:41
  • 1
    Provide reproducible data dput(mydata). Solution would something like as.integer(rowSums(x)>0) Commented Feb 9, 2022 at 13:14
  • @zephryl it is [site, survey, year] Commented Feb 9, 2022 at 14:01
  • 1
    Please have a look at the How to make a great R reproducible example discussion in order to improve your question. Commented Feb 9, 2022 at 14:32

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Yes, that is much better!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.