How to resolve the algorithm Nested templated data step by step in the R programming language
How to resolve the algorithm Nested templated data step by step in the R programming language
Table of Contents
Problem Statement
A template for data is an arbitrarily nested tree of integer indices. Data payloads are given as a separate mapping, array or other simpler, flat, association of indices to individual items of data, and are strings. The idea is to create a data structure with the templates' nesting, and the payload corresponding to each index appearing at the position of each index. Answers using simple string replacement or regexp are to be avoided. The idea is to use the native, or usual implementation of lists/tuples etc of the language and to hierarchically traverse the template to generate the output. Given the following input template t and list of payloads p: The correct output should have the following structure, (although spacing and linefeeds may differ, the nesting and order should follow):
- Generate the output for the above template, t.
- Show which payloads remain unused.
- Give some indication/handling of indices without a payload. Show output on this page.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Nested templated data step by step in the R programming language
Source code in the r programming language
fill_template <- function(x, template, prefix = "Payload#") {
for (i in seq_along(template)) {
temp_slice <- template[[i]]
if (is.list(temp_slice)) {
template[[i]] <- fill_template(x, temp_slice, prefix)
} else {
temp_slice <- paste0(prefix, temp_slice)
template[[i]] <- x[match(temp_slice, x)]
}
}
return(template)
}
library("jsonlite") # for printing the template and result
template <- list(list(c(1, 2), c(3, 4), 5))
payload <- paste0("Payload#", 0:6)
result <- fill_template(payload, template)
cat(sprintf(
"Template\t%s\nPayload\t%s\nResult\t%s",
toJSON(template, auto_unbox = TRUE),
toJSON(payload, auto_unbox = TRUE),
toJSON(result, auto_unbox = TRUE)
))
You may also check:How to resolve the algorithm Remove lines from a file step by step in the Clojure programming language
You may also check:How to resolve the algorithm Execute SNUSP step by step in the J programming language
You may also check:How to resolve the algorithm Text processing/Max licenses in use step by step in the PowerShell programming language
You may also check:How to resolve the algorithm Formatted numeric output step by step in the Stata programming language
You may also check:How to resolve the algorithm Arithmetic/Integer step by step in the Icon and Unicon programming language