Reputation: 473
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)
}
Upvotes: 0
Views: 124
Reputation: 12937
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)
Upvotes: 1
Reputation: 1683
You could create a list to hold dataframes outside of your loop
dataList<-list()
for (i in 1:nrow(newData)){
X<-newData[i,1]
Y<-newData[i,2]
dRatio <- ((X-Xmean)/(Y-Ymean))
dataList[[i]] <- data.frame(X,Y,dRatio)
}
Upvotes: 1