Efficiently fill dataframe with elements based on given row and column indices

Sorry I'm still learning R and new to coding in general and could not find a solution for this elsewhere.

I have a table of elements and their intended row and column indices. I want to create a dataframe output that places each element in its associated row/column position. This was most intuitive for me to do in a nested loop structure as shown below, but is painfully slow especially when iterating over > 100,000 elements and multiple output dataframes.

Is there a way to do this more efficiently using vectorized inputs? I haven't been able to get the syntax to work.

I also tried using apply() but found it difficult since my functions only output a single element not a full dataframe, so it ended up generating a list.

Any help would be greatly appreciated - thank you!

input <- data.frame(Row = rep(c(1:4)), Col = rep(c(1:4),each = 4), 
                    Element = c("a", "aa", "aaa", "aaaa", "b", "bb", "bbb", "bbbb", "c", "cc", "ccc", "cccc", "d", "dd", "ddd","dddd"))

output <- data.frame(matrix(nrow = max(input$Row), ncol = max(input$Col)))
it <- 1
for (r in min(input$Row):max(input$Row)) {
  for (c in min(input$Col):max(input$Col)) {
    output[r,c] <- input$Element[it]
    it <- it+1
  }
}
# Works but too slow for large indices, multiple sets 

output[input$Row, input$Col] <- input$Element
# Error in `[<-.data.frame`(`*tmp*`, input$Row, input$Col, value = c("a",  : 
# duplicate subscripts for columns

output[input[,1:2]] <- input[,3]
# Error in `[.data.frame`(jseq, o) : undefined columns selected
# In addition: Warning messages:
# 1: In matrix(value, n, p) :
#  data length differs from size of matrix: [16 != 4 x 2]
# 2: In xtfrm.data.frame(x) : cannot xtfrm data frames

in place of

output[input$Row, input$Col] <- input$Element

try

 output[cbind(input$Row, input$Col)] <- input$Element
1 Like

This works perfectly and scales much more efficiently for my real problem. It's also correct where my toy example was flipped :sweat_smile: - thank you!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.