Miss Zahrah
Miss Zahrah

Reputation: 39

retrieve the loop output in R

I am new in R and I'm dealing with loops. I have two matrices which are s1 (contain NA values) & B. I've trying this loop and having problem in retrieving the output.

m1<-function(s1,B)
 {
  for(i in 1:nrow(s1))
  { 
   if(is.na(s1[i,])==T) {mi<-rbind(mi,B[i,])}
  }
  print(mi)
 }
outB<-m1(s1,B)

I would like to have a new data.matrix formed from the row binding of the B[i,]. B[i,] should be matching with the s1[i,]. Any help will be appreciated.

Upvotes: 1

Views: 100

Answers (1)

IRTFM
IRTFM

Reputation: 263481

Yeah, that's not really the way to do this in R. This would replace that ugly loop:

m1<-function(s1,B)  # use vector indexing rather than a loop
 { mi <- B[ !is.na(s1),  ] # notice logical index and no "=="
  print(mi)
 }
outB<-m1(s1,B)

You really should not be rbinding successive rows together when all you really wanted to do was select a subset of rows. Extremely inefficient.

Upvotes: 1

Related Questions