Reputation: 15
So I'm trying to do a nested for loop that will multiple 1:100 with 1:100 (10,000 possible combinations). So 1*1, 1*2 ... 1* 100. Once it reaches 100, I want it to repeat, so 2*1, 2*2, 2*100.
Of note: I need to be doing this using for loops
table<-matrix(ncol=3, nrow=100*100)
for (i in 1:100) {
for (z in 1:100){
answer<-i*z
table[i,] <- c(i,z,answer)
}
}
Here's my code above. It seems like an easy fix, but I'm missing something..
Upvotes: 1
Views: 41
Reputation: 887961
We can use outer
out <- outer(1:100, 1:100)
It can be converted to a 3-column data.frame with melt
library(reshape2)
out2 <- melt(out)
In the for
loop, we need
for (i in 1:100) {
for (z in 1:100){
answer<-i*z
table[i, z] <- answer
}
}
table[i, z] <- answer
where
table <- matrix(nrow = 100, ncol = 100)
Checking the output
all.equal(out, table)
#[1] TRUE
If we need the 'i', 'z'
out2 <- transform(expand.grid(i = 1:100, z = 1:100), answer = i * z)
Or with crossing
library(tidyr)
library(dplyr)
crossing(i = 1:100, z = 1:100) %>%
mutate(answer = i * z)
# A tibble: 10,000 x 3
# i z answer
# <int> <int> <int>
# 1 1 1 1
# 2 1 2 2
# 3 1 3 3
# 4 1 4 4
# 5 1 5 5
# 6 1 6 6
# 7 1 7 7
# 8 1 8 8
# 9 1 9 9
#10 1 10 10
# … with 9,990 more rows
Or in a for
loop
table1 <- c()
for(i in 1:100) {
for(z in 1:100){
table1 <- rbind(table1, c(i, z, i * z))
}
}
Upvotes: 1