I am having a difficult time trying to get everything right with nested loops. I feel like I am initializing variables that don't have to be. This code does end up giving me the desired output, but what can be done to improve this? The rep(vec[i], length(vec)) seems janky to me.
Also I can imagine different methods to solve this permutation problem, using replicate or lists, but I am struggling more with how to properly set up nested loops and need help in that context.
vec <- c("red", "blue", "green", "orange")
col2 <- vector()
final <- data.frame(col1 =NULL, col2 = NULL)
for (i in 1:length(vec)){
for (j in 1:length(vec)){
col1 <- rep(vec[i], length(vec))
col2[j] <- vec[j]
temp.df <- cbind(col1, col2)
}
final <- rbind(final, temp.df)
}
final
col1 col2
1 red red
2 red blue
3 red green
4 red orange
5 blue red
6 blue blue
7 blue green
8 blue orange
9 green red
10 green blue
11 green green
12 green orange
13 orange red
14 orange blue
15 orange green
16 orange orange