-3

I am trying to do the following in R.

Along the rows, I have a set values for a variable X. Along the columns, I have a set values for variable y.

For each combination of X and Y, I would like to perform a calculation and then summarize the results in a two-way data table.

One way I thought of was to create a row matrix containing the combination of row and column. Then rbind all the rows. But the process would be tedious and time-consuming. Is there a more efficient way to build this able using R?

Thanks.

stat77
  • 123
  • 1
  • 8
  • 1
    Please provide [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and expected output. Have you tried anything, share your code. – zx8754 Sep 25 '17 at 19:38
  • You could better answers if you would use a more concrete (and better yet reproducible example). But I would urge you to look how functions `spread` and `gather` (from `tidyverse` package) work. They convert data from long to wide format and vice versa. Often it is the easiest to perform the calculations in the long format and then convert it back to wide to get the two way table you are after. – Raivo Kolde Sep 25 '17 at 19:40
  • Thank your for your response and willing to help with seemingly little information. I do understand that reproducible example would help and if I had it, I would have certainly posted it. However, in this case, I had no idea on where to start. So I couldn't even begin. I just know what the final output should look like. So just needed some guidance from you experts. – stat77 Sep 25 '17 at 21:23

1 Answers1

2

What you need is the function outer. Here is a simple example of its use.

x = 1:5
y = seq(1, 9, 2)
names(x) = x
names(y) = y
MyFunction = function(x,y) x^2 + y^2

outer(x, y, MyFunction)
   1  3  5  7   9
1  2 10 26 50  82
2  5 13 29 53  85
3 10 18 34 58  90
4 17 25 41 65  97
5 26 34 50 74 106
G5W
  • 36,531
  • 10
  • 47
  • 80
  • Perfect, G5W! This is exactly what I was looking for. Although my application is different, your code immensely helped. I adapted this to my application and it worked perfectly! THANK YOU once again. I don't think I would have got this one. You have saved a lot of time. Truly appreciate it. – stat77 Sep 25 '17 at 21:52