cabel
cabel

Reputation: 3

Generate list with string keys?

I have two vectors, v1 and v2

v1 <- c('one', 'two', 'three')
v2 <- c('two', 'three', 'four')

I would like to create a list that produces:

"two" : "two", "three" : "three"

Currently, I can only produce this code:

> l <- list()
> l <- c(l, subset(v1, v1 %in% v2)
> l
    [[1]]
    [1] "two"

    [[2]]
    [1] "three"

How can I make the keys be the actually values rather than an index? Thanks.

Upvotes: 0

Views: 260

Answers (1)

IRTFM
IRTFM

Reputation: 263451

I'm not exactly sure what you mean by the 'keys' but am guessing you want the 'names' of the list nodes to be the same as the values:

l <- c(l, subset(v1, v1 %in% v2) )
names(l) <- unlist(l)
 l
$two
[1] "two"

$three
[1] "three"

(I opposed to naming lists 'l' since the l and 1 character are often confusingly similar in the serif fonts. Not to mention the ambiguity of l and I in non-serif fonts.)

Upvotes: 1

Related Questions