0

Really basic question but I can't find an answer - I've probably misunderstood lists in R

Can you have multiple 'nested' items held in a list? This is fine:

cats<-c("red", "blue", "yellow")
l1<-list()

for(i in cats){
  l1[i][1]<-"hello"
};l1

This is not:

for(i in cats){
  l1[i][2]<-"goodbye"
};l1

The output I have in mind would mean

l1$red[1] is "hello" and l1$red[2] is "goodbye"

Am I setting the list up incorrectly? Or is the entire concept flawed?

Thanks

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168
Ed G
  • 802
  • 1
  • 6
  • 19

2 Answers2

0

You have to access the list elements with [[ instead of [:

for(i in cats){
  l1[[i]][1]<-"hello"
};l1

for(i in cats){
  l1[[i]][2]<-"goodbye"
};l1


> l1$red[1]                                                                                                                                                                                                                                                                    
[1] "hello"                                                                                                                                                                                                                                                                    
> l1$red[2]                                                                                                                                                                                                                                                                    
[1] "goodbye"

See also this post which is about how to access list elements.

Community
  • 1
  • 1
user1981275
  • 13,002
  • 8
  • 72
  • 101
  • That's it - thank you. It actually turns out I wanted l1[[i]][[1]]<-"hello" and l1[[i]][[2]]<-"goodbye". This answer got me there. – Ed G Jul 18 '13 at 11:42
0

The data:

cats<-c("red", "blue", "yellow")
words <- c("hello", "goodbye")

You can create the list with this command:

l1 <- setNames(rep(list(words), length(cats)), cats)


> l1
$red
[1] "hello"   "goodbye"

$blue
[1] "hello"   "goodbye"

$yellow
[1] "hello"   "goodbye"

> l1$red[1]
[1] "hello"

> l1$red[2]
[1] "goodbye"
Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168