0

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)
}
1
  • 1
    dataList = cbind(newData[,1], newData[,2], (newData[,1]-Xmean)/(newData[,2]-Xmean)) Commented Oct 21, 2016 at 14:48

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

this create a list, any way to create a data frame?
This will create a list of dataframes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.