0

I want to write a script in R for the following equation and make dataframe for each corresponding result.

x<-c(1:5)
y<-c(1:5)
z<-4*(x+2*y)

I need to locate each result of different combination of value of X & Y, just like an excel table format with Rows/ Columns list from 1 to 5. How can I achieve by using a for loop function. Thanks a lot.

2 Answers 2

4

You don't have to use a loop, use outer

> outer(x, y, FUN=function(x,y){4*(x+2*y)})
     [,1] [,2] [,3] [,4] [,5]
[1,]   12   20   28   36   44
[2,]   16   24   32   40   48
[3,]   20   28   36   44   52
[4,]   24   32   40   48   56
[5,]   28   36   44   52   60
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks very much for your alternative advice!
2

If you're dead-set on doing this with a loop, here's a looping approach to get the same result as with outer:

result_matrix <- matrix(NA, nrow=length(x), ncol=length(y))
for(i in seq(x)) {
for(j in seq(y)) {
    result_matrix[i,j] <- 4*(x[i] + 2*y[j])
}
}

1 Comment

Thanks a lot for your fast response, Dan Y!

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.