user2788464 user2788464 - 1 month ago 5
R Question

R-create a data frame inside this loop

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

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)