1

I'm new to R. In the code I need to create a list of vectors(like tuples in python), which is named e. I find I cannot add new element, i.e. a vector to the list, in this way: e[i]<-c(5,3); the result shows only 5 is added to the list and there is a warning message: "number of items to replace is not a multiple of replacement length". How can I solve this problem? enter image description here

fatcat
  • 33
  • 4
  • 2
    Use double square brackets: `e[[4]]<-c(5,3)`. – nicola Jan 12 '21 at 14:13
  • 1
    Please do not post an image of code/data/errors: it cannot be copied or searched (SEO), it breaks screen-readers, and it may not fit well on some mobile devices. Ref: https://meta.stackoverflow.com/a/285557 (and https://xkcd.com/2116/). Please just include the code, console output, or data (e.g., `data.frame(...)` or the output from `dput(head(x))`) directly. – r2evans Jan 12 '21 at 14:20
  • Search for "append", try: `c(e, list(c(5,3)))` or `append(e, list(c(5,3)))` – zx8754 Jan 12 '21 at 14:25

2 Answers2

3

Try this with double bracket for lists as @Nicola suggested in comments:

#Data
e <- list(c(0,1),c(1,3),c(4,0))
#Add
e[[4]] <- c(5,3)

Output:

e
[[1]]
[1] 0 1

[[2]]
[1] 1 3

[[3]]
[1] 4 0

[[4]]
[1] 5 3

It can also work:

#Code2
e <- c(e,list(c(5,3)))
Duck
  • 39,058
  • 13
  • 42
  • 84
2

You should use list when with [

e[4] <- list(c(5, 3))

since [ store data in terms of list in your case.


Or just [[ for assignment

e[[4]] <- c(5,3)

You can type ?[ and read for more information.

ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81