Search code examples
rfor-loopdataframematrixoperation

How do you fill in an empty data frame based on an index in R?


I'm trying to create an empty data frame then have it filled in based on this for loop.

I want to have a data frame by the dimensions 5x10, which contains the result of the multiplication of the each number in the vectors A and B.

This what I want the end data frame to look like.

This what I want the end data frame to look like.

So far I'm using a for loop to calculate the product of the 2 vectors but I am not able to insert the result I want into the data frame.

Where am I going wrong?

My Code:

a <- c(1:10)
b <- c(1:5)

#Make a dummy dataframe filled with zeros, thats length(a) long and length(b) high     
dummy <- as.data.frame(matrix(0, ncol=5, nrow=10))

heatmap_prep <- function(vector_a,vector_b){
        for (i in 1:length(a)){
            first_number <- a[i]
        for(j in 1:length(b)){
            second_number <- b[j]
            result <- first_number*second_number
            dummy [i,j] <- result
            print(result)
        }
    }
}

Thanks!


Solution

  • Functions don't modify things outside of the function. You should create dummy inside the function, and return the final modified version at the end of your function:

    heatmap_prep <- function(vector_a,vector_b){
        dummy <- as.data.frame(matrix(0, ncol=length(vector_b), nrow=length(vector_a)))
        for (i in 1:length(a)){
            first_number <- a[i]
            for(j in 1:length(b)){
                second_number <- b[j]
                result <- first_number*second_number
                dummy [i,j] <- result
                print(result)
            }
        }
        return(dummy)
    }
    heatmap_prep(a, b)
    #    V1 V2 V3 V4 V5
    # 1   1  2  3  4  5
    # 2   2  4  6  8 10
    # 3   3  6  9 12 15
    # 4   4  8 12 16 20
    # 5   5 10 15 20 25
    # 6   6 12 18 24 30
    # 7   7 14 21 28 35
    # 8   8 16 24 32 40
    # 9   9 18 27 36 45
    # 10 10 20 30 40 50
    

    However, in this case the built-in outer function is much more succinct. The output is a matrix, but you can easily coerce it to a data.frame.

    outer(a, b)
    #       [,1] [,2] [,3] [,4] [,5]
    #  [1,]    1    2    3    4    5
    #  [2,]    2    4    6    8   10
    #  [3,]    3    6    9   12   15
    #  [4,]    4    8   12   16   20
    #  [5,]    5   10   15   20   25
    #  [6,]    6   12   18   24   30
    #  [7,]    7   14   21   28   35
    #  [8,]    8   16   24   32   40
    #  [9,]    9   18   27   36   45
    # [10,]   10   20   30   40   50
    

    You can also think of this problem as matrix multiplication. This will give the same result.

     a %*% t(b)