elyraz
elyraz

Reputation: 473

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)
}

Upvotes: 0

Views: 124

Answers (2)

989
989

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

user124123
user124123

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

Related Questions