Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

R extract data by for loop

I have a large number of matrix, calls train 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 I want my list1 to contain (1,1,1,1,1,1,1) and list2 to contain (0,0,0,0)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Perhaps you don't need a for loop, just select your data using a logical evaluation. By the way, the data structure you want in R is called vector, not list. Please refer to this website (http://www.programcreek.com/2014/01/vector-array-list-and-data-frame-in-r/) for more information.

list1 <- train[train == 1]
list2 <- train[train == 0]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...