yungarlos
yungarlos

Reputation: 31

R list appending i.e. appending to an existing list

Now, normally I would use JSON or data.frames, but my course specifically asks to store a name and Movie table in a named list. I struggle to append to the list.

Here is my implementation:

demoList <- list(
    name = c("Doug", "Steven"), 
    movies = list( c("Gremlins", "Cars", "1984"), c("Freaky Friday", "Hitchhiker's Guide")))

i.e. I have Hector, and his movies would be ("Jurassic Park", "Jaws".)

When I try to add Herbert to the name vector it overwrites my vector. i.e.

demoList$[5] <- Hector

Appending to demoList$movies would probably follow the same conventions.

All of the R forums I searched created new $variables for appending, so would my issue be that I chose the wrong representation of the data in the named list?

Upvotes: 1

Views: 59

Answers (1)

akrun
akrun

Reputation: 887881

We could use Map to append

demoList <- Map(append, demoList, list("Hector", list(c("Jurassic Park", "Jaws"))))
demoList
#$name
#[1] "Doug"   "Steven" "Hector"

#$movies
#$movies[[1]]
#[1] "Gremlins" "Cars"     "1984"    

#$movies[[2]]
#[1] "Freaky Friday"      "Hitchhiker's Guide"

#$movies[[3]]
#[1] "Jurassic Park" "Jaws"         

Upvotes: 1

Related Questions