Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201867

transforming R function output to match format of Python function output

$
0
0

translating a Python function to R I try to add more data while iterating through values which I split using strsplit() in R. The return value of the original Python function is a list of lists so this should be the same in the R version (vector of vectors). The Python function is

anbaudauer = 12
planzen_list = [
                    'tomaten_6',
                    'karotten_4',
                    'paprika_7',
                    'erdbeeren_5',
                    'koriander_2',
                    'salat_3',
                    'zucchini_4',
                    'gurke_5',
                    'petersilie_2',
                    'radieschen_3'
                ]

def possible_combinations(values, target, with_replacement=True):
    def sub_combinations(index, l, r, t, w):
        if t == sum(filter(lambda i: isinstance(i, int), l)):
            r.append(l)
        elif t < sum(filter(lambda i: isinstance(i, int), l)):
            return
        for u in range(index, len(values)):
            sub_combinations(u if w else (u + 1), l + [values[u].split('_')[0], int(values[u].split('_')[1])], r, t, w)
        return r
    return sub_combinations(0, [], [], target, with_replacement)

raw_combinations = possible_combinations(planzen_list, anbaudauer)

# returns [['tomaten', 6, 'tomaten', 6], ['tomaten', 6, 'karotten', 4, 'koriander', 2], ['tomaten', 6, 'karotten', 4, 'petersilie', 2], ...]

the current state of the R function is

w <- c(
  'tomaten_6',
  'karotten_4',
  'paprika_7',
  'erdbeeren_5',
  'koriander_2',
  'salat_3',
  'zucchini_4',
  'gurke_5',
  'petersilie_2',
  'radieschen_3'
)
n <- length(w)
t <- 12
D <- list()
for (j in 0:n) D[[paste(0, j)]] <- list(c())
for (i in 1:t) D[[paste(i, 0)]] <- list()
for (j in 1:n) {
  for (i in 1:t) {
    D[[paste(i, j)]] <- do.call(c, lapply(0:floor(i/as.numeric(strsplit(w[j], '_')[[1]][2])), function(r) {
      lapply(D[[paste(i-r*as.numeric(strsplit(w[j], '_')[[1]][2]), j-1)]], function(x) c(x, rep(strsplit(w[j], '_')[[1]][1]), r))
    }))
  }
}
D[[paste(t, n)]]

at as.numeric(strsplit(w[j], '_')[[1]][2])I would like to add the name of the vegetable before the number. In essence the R function should return the same as the Python function. Transforming the R functions return value was tricky so far. Basically I tried taking everything apart and stitching it together again. As I haven't used R in a long time I'm sure there is a convenient method to get the same data returned as from the Python function.


Viewing all articles
Browse latest Browse all 201867

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>