Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

r - Extract data by for loop

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...