1

Suppose I have a vector of dimension n and it is composed of 0 and 1. Then I divide this vector into m equal bins. A bin is called active if it contains at least one "1". I want to write a command that returns the place of active bins and how many "1" they contain.

For example, I have this vector: n=15, m=5

[1 0 0 | 0 1 1 | 0 0 0 | 0 1 0| 1 1 1] 

I want to have matrix [1 2 4 5] (the active bins) and [1 2 1 3] (how many 1 they contain).

Can I write this in R without using for loops?

1
  • Probably. (Just btw, is this homework?) Commented Apr 24, 2012 at 16:33

2 Answers 2

4

I would do it like this:

a <- c(1,0,0,0,1,1,0,0,0,0,1,0,1,1,1) m <- 5 idx <- rep(1:m, each=length(a)/m) # how many ones? no <- sapply(1:5, function(x) sum(a[idx==x])) # which bins contain ones? bins <- 1:m bins[no>0] 
Sign up to request clarification or add additional context in comments.

1 Comment

or no <- rowSums(matrix(a,ncol=3,byrow=TRUE)); which(no>0); no[no>0]
1

Another approach to obtain the vector with number of ones:

x <- c(1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1) n <- length(x) m <- 5 size <- n/m x.list <- split(x, cut(seq_along(x)/size, 0:m)) vapply(x.list, sum, 0) 

From there, do as jigr does.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.