0

I am stuck on a problem where I create a nested list. My code looks like this:

steps = ["one", "two"]
whats = ["dog", "cat"]
keys = ["young", "old", "justborn"]
sol<-list() for (step in steps) {
    sol[step]<-list()
    for (what in whats) {
      tmp <-list()
      for (key in keys){
        tmp[key] <- data$value
      }
      (sol[sol$step==step])[what] = tmp #Here error occurs
    }   
}

The error that I get is the following:

number of items to replace is not a multiple of replacement length

At that moment the output for tmp is the following:

> tmp
$after
[1] "12"

$message
[1] "Good job"

$solution
[1] "Friday"

I have seen that there are a lot of posts with the same error messages, but I still cannot figure out what is my problem. Many of the solutions that I have seen on other posts are based on having NA but my data set does not have any.

  • Your line, `sol$step` is taken literally as the element named `step` -- not the variable. Replace with `sol[[step]]`, so the comparison is `sol[sol[[step]] == step]]`. Look up the difference between using single and double square brackets on a list, i.e. `sol[step]` vs. `sol[[step]]`. You might have same issue with `[what]`. – MrGumble Jun 01 '22 at 11:59
  • Also note that R works inherently on vectors, so your for-loops are mostly unnecessary and can be replaced by `lapply` and the vectors `whats`, `steps`, and `keys`. – MrGumble Jun 01 '22 at 12:01
  • Note too that you cannot make arrays/vectors with brackets alone like in Python. You'll e.g. need `steps <- c("one", "two")` not `steps <- ["one", "two"]`. – harre Jun 01 '22 at 12:02
  • 1
    Lastly, see https://stackoverflow.com/a/5963610/882102 for improving your question -- we cannot guess what you have in `data` nor what output you expect. Literally, how many lists deep? – MrGumble Jun 01 '22 at 12:02
  • @MrGumble thank you for your comments. I have improved the code accordingly with the double brackets and now I get `Error in (sol[sol[[step]] == step])[[what]] = tmp : could not find function "(<-"` when I execute that line. About `lapply` and creating arrays/vectors I have to apologize, I am new with R and kind of learning while doing :D – Tricker Macedonia Jun 01 '22 at 12:04
  • 1
    No need to apologise. We were all new to R at some point. Please update your question according to the link I sent you, including with your updated code. The latest error you report is due to your code having incorrect syntax, e.g. you are missing a start or end bracket or parenthesis. Also, @harre - I cannot believe I oversaw the square brackets thing! – MrGumble Jun 01 '22 at 12:07

0 Answers0