-6

I have a large number of matrix, calls train$X which is a binary data with 1 and 0

I want to extract and make another two lists which contains 1 as list1 and 0 as list2 by using for loop

my R code is not working

X <- c(0,1,0,1,0,1)
Y <- c(1,1,1,1,1,0)
train<- as.matrix (cbind(X,Y))
list1 <- list()
list2 <- list()

for(i in 1:length(train)) {
  if(train[i]== 1)
    list1 = train[i]
 else
    list2 = train[i]

}

Therefore list1 contains (1,1,1,1,1,1,1) list2 contains (0,0,0,0)

AAA
  • 83
  • 8

1 Answers1

1

I don't think the best way is a loop, it isn't a list that you want but a vector object, I propose to use == on a matrix as following :

X <- c(0,1,0,1,0,1)
Y <- c(1,1,1,1,1,0)
train <- cbind(X,Y)

v1 <- train[train == 1]
v2 <- train[train == 0] 

If you really want a loop :

v1 <- c() # It is not necessary
v2 <- c() # It is not necessary

for(i in 1:nrow(train)){
  for(j in 1:ncol(train)){
    if(train[i, j] == 1){
      v1 <- c(v1, train[i, j])
    }else{
      v2 <- c(v2, train[i, j])
    }
  }
}

A last solution but not least :

v1 <- rep(1, sum(train == 1))
v2 <- rep(0, sum(train == 0))

So their is a lot of differents solutions to do it.

Rémi Coulaud
  • 1,684
  • 1
  • 8
  • 19