How to convert a named vector to a list in R?


A named vector cannot be directly converted to a list because we would need to un-name the vector names and convert those names to names of the list elements. This can be done by using lapply function function. For example, suppose we have a named vector x then it can be converted to a list by using the command x<-lapply(split(x,names(x)),unname)

Example1

Live Demo

> x1<-1:26
> names(x1)<-LETTERS[1:26]
> x1

Output

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26

Example

> List_x1<-lapply(split(x1,names(x1)),unname)
> List_x1

Output

$A
[1] 1

$B
[1] 2

$C
[1] 3

$D
[1] 4

$E
[1] 5

$F
[1] 6

$G
[1] 7

$H
[1] 8

$I
[1] 9

$J
[1] 10

$K
[1] 11

$L
[1] 12

$M
[1] 13

$N
[1] 14

$O
[1] 15

$P
[1] 16

$Q
[1] 17

$R
[1] 18

$S
[1] 19

$T
[1] 20

$U
[1] 21

$V
[1] 22

$W
[1] 23

$X
[1] 24

$Y
[1] 25

$Z
[1] 26

Example2

Live Demo

> x2<-rnorm(50,47.5,3.26)
> x2

Output

[1]  43.67579 46.84597 50.08969 48.86948 48.27692 48.99517 50.50144 43.50225
[9]  48.57954 43.04919 49.37592 39.46386 45.92388 43.73156 47.05908 44.59190
[17] 43.00546 46.63213 45.39842 47.19159 48.08059 48.31393 50.96543 48.27077
[25] 50.11419 52.72060 52.27889 48.02022 45.90482 47.81138 55.45007 51.79651
[33] 44.89771 43.15016 47.74477 48.08014 51.54148 48.72756 47.42376 45.41104
[41] 49.24270 47.75459 48.58061 47.46924 43.92129 43.99410 45.99165 48.07986
[49] 43.44653 48.49270

Example

> names(x2)<-sample(c("G1","G2","G3","G4","G5"),50,replace=TRUE)
> x2

Output

G3 G5 G3 G1 G5 G4 G2 G5
43.67579 46.84597 50.08969 48.86948 48.27692 48.99517 50.50144 43.50225
G4 G3 G4 G1 G2 G4 G5 G5
48.57954 43.04919 49.37592 39.46386 45.92388 43.73156 47.05908 44.59190
G5 G4 G5 G2 G4 G2 G4 G5
43.00546 46.63213 45.39842 47.19159 48.08059 48.31393 50.96543 48.27077
G1 G5 G5 G3 G2 G2 G5 G2
50.11419 52.72060 52.27889 48.02022 45.90482 47.81138 55.45007 51.79651
G3 G4 G4 G3 G3 G2 G2 G4
44.89771 43.15016 47.74477 48.08014 51.54148 48.72756 47.42376 45.41104
G1 G4 G4 G5 G2 G1 G1 G5
49.24270 47.75459 48.58061 47.46924 43.92129 43.99410 45.99165 48.07986
G2 G3
43.44653 48.49270

Example

> List_x2<-lapply(split(x2,names(x2)),unname)
> List_x2

Output

$G1
[1] 48.86948 39.46386 50.11419 49.24270 43.99410 45.99165

$G2
[1] 50.50144 45.92388 47.19159 48.31393 45.90482 47.81138 51.79651 48.72756
[9] 47.42376 43.92129 43.44653

$G3
[1] 43.67579 50.08969 43.04919 48.02022 44.89771 48.08014 51.54148 48.49270

$G4
[1] 48.99517 48.57954 49.37592 43.73156 46.63213 48.08059 50.96543 43.15016
[9] 47.74477 45.41104 47.75459 48.58061

$G5
[1] 46.84597 48.27692 43.50225 47.05908 44.59190 43.00546 45.39842 48.27077
[9] 52.72060 52.27889 55.45007 47.46924 48.07986

Updated on: 23-Nov-2020

329 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements