user2788464 - 10 months ago 71

R Question

How can I create a data frame inside this loop based on the calculated variables?

Script:

`for (i in 1:nrow(newData)){`

X<-newData[i,1]

Y<-newData[i,2]

dRatio <- ((X-Xmean)/(Y-Ymean))

dataList <- data.frame(X,Y,dRatio)

}

Answer Source

Try this vectorized:

```
dataList <- newData[,1:2]
dataList$dRatio <- ((newData[,1]-Xmean)/(newData[,2]-Ymean))
```

Or if you persist to use your own code:

```
m <- matrix(0, nrow(newData), 3)
for (i in 1:nrow(newData)){
X<-newData[i,1]
Y<-newData[i,2]
dRatio <- ((X-Xmean)/(Y-Ymean))
m[i,] <- c(X,Y,dRatio)
}
dataList <- as.data.frame(m)
```