Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting elements in an R list

I want to store a few entries in a "dictionary" so that I can retreive them by name. I can form something like that indirectly like this:

> a = list(c(1,2),c(9,9,0,0))
> names(a) = c("first","second")
> a
$first
[1] 1 2

$second
[1] 9 9 0 0

However, I can't do the same thing by simply inserting them by name like this:

> a=list()
> a["first"] = c(1,2)
Warning message:
In a["first"] = c(1, 2) :
  number of items to replace is not a multiple of replacement length
> a
$first
[1] 1

Why is this so, and what syntax should I use to insert objects like vectors or matrices by name into a list?

like image 513
highBandWidth Avatar asked Apr 27 '26 11:04

highBandWidth


2 Answers

Your problem is that you are using [ rather than [[. This should work:

a[['first']] <- c(1,2)

as should this:

a$first <- c(1,2)

Remember, [ gives you a sublist, while [[ accesses specific elements.

like image 179
joran Avatar answered Apr 29 '26 00:04

joran


You got one good answer. Here's an equivalent answer:

 a=list()
 a["first"] = list(c(1,2))
 a
# $first
# [1] 1 2

So to expand on joran's perfectly fine answer, you are really using [<- as a function, and it both gives (via [) and receives (via[<-) lists.

Just because a function returns something is not a promise that it will set something.

like image 36
IRTFM Avatar answered Apr 29 '26 01:04

IRTFM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!