clairsang
clairsang

Reputation: 125

Convert dataset to binary

First, I've a vector s = c(0,2,4,2,2,4,3,6,7). I wrote the code:

  s1 <- as.factor(s)
  n <- length(s1)
  x <- matrix(0, n, length(levels(s1)))
  x[(1:n) + n*(unclass(s1)-1)] <- 1

Next, I obtained a matrix:

> x
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    0    0    0    0    0
 [2,]    0    1    0    0    0    0
 [3,]    0    0    0    1    0    0
 [4,]    0    1    0    0    0    0
 [5,]    0    1    0    0    0    0
 [6,]    0    0    0    1    0    0
 [7,]    0    0    1    0    0    0
 [8,]    0    0    0    0    1    0
 [9,]    0    0    0    0    0    1

But, now, I want to change the contraint: in a column of matrix, for example column 1: x[i,1] = 1 if and only if s[i] > s[1], else x[i,1] = 0. And if s[1]= 0, so all others x[i,1] = 1 except s[i] = 0.

In this example, I want to obtain a matrix:

      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    0    0    0    0    0    0
 [2,]    1    0    0    0    0    0
 [3,]    1    1    1    0    0    0
 [4,]    1    0    0    0    0    0
 [5,]    1    0    0    0    0    0
 [6,]    1    1    1    0    0    0
 [7,]    1    1    0    0    0    0
 [8,]    1    1    1    1    1    0
 [9,]    1    1    1    1    1    0

Thanks.

Upvotes: 0

Views: 1036

Answers (1)

sgibb
sgibb

Reputation: 25736

I am not sure that I understand your question right (and my final matrix looks a little bit different):

s <- c(0,2,4,2,2,4,3,6,7)
us <- unique(s)
sapply(seq_along(us), function(i)ifelse(s > us[i], 1, 0))

#       [,1] [,2] [,3] [,4] [,5] [,6]
# [1,]    0    0    0    0    0    0
# [2,]    1    0    0    0    0    0
# [3,]    1    1    0    1    0    0
# [4,]    1    0    0    0    0    0
# [5,]    1    0    0    0    0    0
# [6,]    1    1    0    1    0    0
# [7,]    1    1    0    0    0    0
# [8,]    1    1    1    1    0    0
# [9,]    1    1    1    1    1    0

Upvotes: 1

Related Questions