将数据集转换为二进制

时间:2014-03-19 10:35:12

标签: r converter

首先,我有一个向量s = c(0,2,4,2,2,4,3,6,7)。 我写了代码:

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

接下来,我获得了一个矩阵:

> 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

但是,现在,我想改变约束: 在矩阵列中,例如列1:x [i,1] = 1当且仅当s [i]> 1时s [1],否则x [i,1] = 0.如果s [1] = 0,那么所有其他x [i,1] = 1除了s [i] = 0。

在这个例子中,我想获得一个矩阵:

      [,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

感谢。

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解你的问题(我的最终矩阵看起来有点不同):

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