3

I have a named vector that I want to convert to a list, as such:

a = 1:10
names(a) = letters[1:10]
as.list(a)
$a
[1] 1
$b
[1] 2
$c
[1] 3

Here, the names of each vector is now the name of the list, but I need the vectors within the list to keep their names, like this:

as.list(a)
$a
a
1
$b
b
2
$c
c
3

Any ideas? Thanks!

Haloom
  • 350
  • 3
  • 9
  • 2
    My question is very different. The solutions posted below (which are simple and worked) were not mentioned at all in that question. – Haloom Oct 13 '17 at 04:14
  • Did you check the first and accepted solution in that question? You can easily adapt it to your requirement for this question. – Ronak Shah Oct 13 '17 at 04:15
  • 1
    I reopened this question. I don't believe it's a duplicate of the linked question, and 4 out of the 5 duplicate voters were not R users. You can derive answers from other answers all over this site, but that does not mean the questions are duplicates of each other. If you can get 5 R users to agree to that duplicate then I might change my mind. – Rich Scriven Oct 13 '17 at 23:03

2 Answers2

5

You can use split().

split(a, names(a))
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
0

One option after going ahead with as.list is to the set the names of the elements with the corresponding names of original vector with Map

Map(setNames, as.list(a), names(a))
#$a
#a 
#1 

#$b
#b 
#2 

#$c
#c 
#3 

#$d
#d 
#4 

#$e
#e 
#5 

#$f
#f 
#6 

#$g
#g 
#7 

#$h
#h 
#8 

#$i
#i 
#9 

#$j
# j 
#10 
akrun
  • 874,273
  • 37
  • 540
  • 662