运行循环时出错

时间:2018-08-12 22:27:44

标签: r loops vector binary

我正在用R编程,我有184个具有0或正值的向量。我想将它们转换为二进制值向量,然后创建一个矩阵。

下面是这些变量之一的示例

     >E1
     [1]  0  0  0  0  0  0  0  0  0 26  0  0  0  0  0  0  0  0  0  0  2  0  
      0  0  0  0  0  0
     [29]  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  
      0  0  0  0  0  0
     [57]  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  
      0  0  0  0  0  0
     [85]  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  2  
      0  0  0  0  0  0
     [113]  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  
      0  0  0  0  0  0  0
     [141]  0  0  0  0  0  0  0  0  0  0  0  0  4  0  0  0  0  0  0  0  0  0  
      0  0  0  0  0  0
     [169]  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0

这是我的代码:

for (i in 1:184){
                 if ( get(paste("E",i,sep="") )>0){

               assign(paste("C",i,sep=""),1)} else{
               assign(paste("C",i,sep=""),0)
                                      }
    }

问题在于生成的C1,C2 ... C184不是向量,而只是数字值。我该如何解决并获得向量?以及如何使用184个二进制值向量制作数据框?

谢谢

2 个答案:

答案 0 :(得分:0)

看看是不是

E1 = round(runif(15, 0, 3))
E2 = round(runif(15, 0, 4))
E183 = round(runif(15, 0, 5))
E184 = round(runif(15, 0, 5))

(data = data.frame(E1, E2, E183, E184))
#   E1 E2 E183 E184
#1   1  3    3    3
#2   0  1    1    3
#3   1  2    3    1
#4   2  1    3    1
#5   2  4    0    0
#6   3  4    4    2
#7   1  3    3    2
#8   1  3    5    5
#9   3  3    1    3
#10  1  1    3    1
#11  2  3    1    0
#12  1  2    3    4
#13  0  1    2    3
#14  3  4    2    2
#15  2  4    2    5

data[data > 0] = 1

colnames(data) = c("C1", "C2", "C183", "C184")

data 
#   C1 C2 C183 C184
#1   1  1    1    1
#2   0  1    1    1
#3   1  1    1    1
#4   1  1    1    1
#5   1  1    0    0
#6   1  1    1    1
#7   1  1    1    1
#8   1  1    1    1
#9   1  1    1    1
#10  1  1    1    1
#11  1  1    1    0
#12  1  1    1    1
#13  0  1    1    1
#14  1  1    1    1
#15  1  1    1    1

答案 1 :(得分:0)

您可以避免使用循环并获得结果。由于您只有正数和零,并且希望将所有正数转换为1,因此可以使用函数符号并将其应用于数据库,该数据库可以从向量到函数应用程序的前面构造而成。代码示例如下所示(在示例中,矢量组合为行,但也可以组合为列):

    V1<- c(0,0,0,0,0,0,0,0,0,26,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0)
    V2 <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 ,0,0,0,0,0,0)
    V3 <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
    V4 <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2, 0,0,0,0,0,0)
    V5 <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0)
    V6 <- c(0,0,0,0,0,0,0,0,0,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)

    dat <- as.data.frame(rbind(V1, V2, V3, V4, V5, V6))
    dat <- as.matrix.data.frame(sapply(dat, sign ))