# How to convert two columns of an R data frame to a named vector?

If two columns are of a form such that one column contains the name of the vector values and another column having the values of a vector then we might want to convert them into a vector. To do this, we can simply read the vectors with their data type and structure them with structure function.

## Example 1

Live Demo

x1<-rep(c("C1","C2","C3","C4"),each=5)
x2<-rep(1:10,2)
df1<-data.frame(x1,x2)
df1

## Output

x1 x2
1 C1 1
2 C1 2
3 C1 3
4 C1 4
5 C1 5
6 C2 6
7 C2 7
8 C2 8
9 C2 9
10 C2 10
11 C3 1
12 C3 2
13 C3 3
14 C3 4
15 C3 5
16 C4 6
17 C4 7
18 C4 8
19 C4 9
20 C4 10
df1_vector<-structure(as.numeric(df1$x2),names=as.character(df1$x1))
df1_vector
C1 C1 C1 C1 C1 C2 C2 C2 C2 C2 C3 C3 C3 C3 C3 C4 C4 C4 C4 C4
1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 10

## Example 2

Live Demo

set.seed(111)
y1<-LETTERS[1:20]
y2<-rnorm(20,0.5)
df2<-data.frame(y1,y2)
df2

## Output

y1 y2
1 A 0.735220712
2 B 0.169264128
3 C 0.188376176
4 D -1.802345658
5 E 0.329123955
6 F 0.640278225
7 G -0.997426656
8 H -0.510188419
9 I -0.448475605
10 J 0.006037783
11 K 0.326325872
12 L 0.093401220
13 M 2.345636264
14 N 0.894054110
15 O 1.297528501
16 P -1.066665360
17 Q 0.414148991
18 R 0.140860519
19 S -0.693608967
20 T 0.864186737
df2_vector<-structure(as.numeric(df2$y2),names=as.character(df2$y1))
df2_vector
A B C D E F
0.735220712 0.169264128 0.188376176 -1.802345658 0.329123955 0.640278225
G H I J K L
-0.997426656 -0.510188419 -0.448475605 0.006037783 0.326325872 0.093401220
M N O P Q R
2.345636264 0.894054110 1.297528501 -1.066665360 0.414148991 0.140860519
S T
-0.693608967 0.864186737

## Example 3

Live Demo

z1<-rep(c("String1","String2","String3","String4","String5"),each=4)
z2<-letters[20:1]
df3<-data.frame(z1,z2)
df3

## Output

z1 z2
1 String1 t
2 String1 s
3 String1 r
4 String1 q
5 String2 p
6 String2 o
7 String2 n
8 String2 m
9 String3 l
10 String3 k
11 String3 j
12 String3 i
13 String4 h
14 String4 g
15 String4 f
16 String4 e
17 String5 d
18 String5 c
19 String5 b
20 String5 a
df3_vector<-structure(as.character(df3$z2),names=as.character(df3$z1))
df3_vector
String1 String1 String1 String1 String2 String2 String2 String2 String3 String3
"t" "s" "r" "q" "p" "o" "n" "m" "l" "k"
String3 String3 String4 String4 String4 String4 String5 String5 String5 String5
"j" "i" "h" "g" "f" "e" "d" "c" "b" "a"

Updated on: 21-Aug-2020

314 Views