thothal
thothal

Reputation: 20329

Transform a named vector to a named list

How to transform this:

inp <- c(a = 1, b = 2, c = 3, d = 4)

into this:

list(aa = c(a = 1), bb = c(b = 2), cc = c(c = 3), dd = c(d = 4))

purrr::imap(as.list(r), ~ set_names(.x, .y)) is a good start, but the loop seems to be unnecessary. Any ideas?

Upvotes: 2

Views: 47

Answers (2)

akrun
akrun

Reputation: 887118

We can use

Map(setNames, setNames(inp, strrep(letters[1:4], 2)), names(inp))

-output

#$aa
#a 
#1 

#$bb
#b 
#2 

#$cc
#c 
#3 

#$dd
#d 
#4 

Upvotes: 1

Duck
Duck

Reputation: 39595

An option can be:

#Code
res <- setNames(split(inp,names(inp)),paste0(names(split(inp,names(inp))),names(split(inp,names(inp)))))

Output:

$aa
a 
1 

$bb
b 
2 

$cc
c 
3 

$dd
d 
4 

The more compact solution would be (Many thanks and credits to @markus):

#Code2
res <- setNames(split(inp , names(inp)), strrep(names(inp), 2))

Same output.

Upvotes: 2

Related Questions