Question

I'm trying to do this simple task, all the variables are initialized properly, but for some reason this isn't working. What am I doing wrong?

for(i in 1:117) 
  {x = runif(1,0,1)
   if(x<0.5) 
     testframe = rbind(utilities[i,]) 
   else 
     trainframe = rbind(utilities[i,])}
Was it helpful?

Solution

In your loop, you overwrite both testframe and trainframe in each run of the loop. You could use testframe <- rbind(testframe, utilities[i, ]), but this would be quite inefficient.

Here's another approach without loops:

x <- sample(c(TRUE, FALSE), 117, replace = TRUE)

testframe <- utilities[x, ]
trainframe <- utilities[!x, ]

You can also create a list including the two subsets (based on vector x):

split(utilities, x)

OTHER TIPS

If you insist to use a for loop, you can always save your outcome as an empty list and add items to that list:

Here's an untested example (as I do not have the "utilities" data):

testframe <- list()
trainframe <- list()

for(i in 1:117) 
  {x = runif(1,0,1)
   if(x<0.5) 
     testframe[i] <- utilities[i,] ##whatever you want to save here
   else 
     trainframe = utilities[i,]
}

Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top