neticin
neticin

Reputation: 159

vector manipulation in R

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?

Upvotes: 1

Views: 284

Answers (2)

Henrik
Henrik

Reputation: 14450

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.

Upvotes: 1

johannes
johannes

Reputation: 14433

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]

Upvotes: 4

Related Questions