jane
jane

Reputation: 567

R- store data as data.frame in a loop

Is there a better way to store the data generated in the loop as data.frame (but still using a loop)?

script:

resX<-c()
resY<-c()
Mystep <- 2 

for(i in seq(0, 10, by = Mystep  )){
  resX[i]  <-i*10
  resY[i]  <-i/10     
}

Results<-as.data.frame(cbind(resX,resY))

Upvotes: 0

Views: 85

Answers (2)

AdamO
AdamO

Reputation: 4930

Using a loop is not using R efficiently. The vectorized solution is the right answer. But since that is off the table, I don't think a double-loop solution is out of line:

data.frame(
  sapply(seq(0, 10, by = Mystep), `*`, 10)),
  sapply(seq(0, 10, by = Mystep), `/`, 10))
)

Or (cleaner)

itr <- seq(0, 10, by = Mystep)
data.frame(sapply(itr, `*`, 10)), sapply(itr, `/`, 10)))

And lastly with a for loop:

output <- data.frame(numeric(length(itr)), numeric(length(itr)))
for(i in itr) {
  output[i, 1] <- itr*10
  output[i, 2] <- itr/10
}

Upvotes: 0

Felipe Alvarenga
Felipe Alvarenga

Reputation: 2652

If you really want to use a loop, guess this one works

Results <- data.frame()
Mystep <- 2 

for(i in seq(0, 10, by = Mystep  )){
  xy = c(i*10, i/10)

  Results = rbind(Results, xy)    
}

names(Results) = c("X", "Y")
> Results
    X  Y
1   0  0.0
2  20  0.2
3  40  0.4
4  60  0.6
5  80  0.8
6 100  1.0

Upvotes: 1

Related Questions