bstockton
bstockton

Reputation: 577

Putting Results of for loop into a data frame in R

I have a function that will return a numeric class object, here is a simplified version:

count.matches <- function(x) {
  ifelse(!is.na(a[,x] & a[,2]),1,0)
}

it just produces an object of 0s and 1s. For example

count.matches(4)
[1] 0 0 0 0 1 1 0

I just want to do a simple for loop of this function and store the results in a data frame, i.e. each time the function loops through create a column, however I am having trouble.

p <- data.frame()
my.matches <- for(i in 2:100) { 
  p[i,] <- count.matches(i)
 }

This produces nothing. Sorry if this is a really stupid question, but I have tried a bunch of things and nothing seems to work. If you need any more information, please let me know and I will provide it.

Upvotes: 2

Views: 11420

Answers (1)

Scott Ritchie
Scott Ritchie

Reputation: 10543

for does not return the last value in the loop and combine the results. It returns NULL.

Using for you will have to create the data.frame first, and fill it with the results:

my.matches <- as.data.frame(matrix(0, nrow(a), ncol(a) - 1))
for (i in 2:100) {
  my.matches[,i] <- count.matches(i)
}

Alternative you could use the foreach package, which provides the functionality you're expecting from for.

library(foreach)
my.matches <- foreach(i = 2:100, .combine=data.frame) %do% {
  count.matches(i)
}

Upvotes: 5

Related Questions