Sati
Sati

Reputation: 726

Assign vector values to one another

I have two vectors:

A = c(letters[1:4])
B = c(1,2,3,4)

How can I code so that each value in B is correspondingly assigned to A as such?

a <- 1
b <- 2
...

Upvotes: 3

Views: 1773

Answers (2)

h3rm4n
h3rm4n

Reputation: 4187

Or:

names(B) <- A

The result:

> B
a b c d 
1 2 3 4 

> B['b']
b 
2

Upvotes: 3

akrun
akrun

Reputation: 886948

We can use assign

for(i in seq_along(A)) assign(A[i], B[i])
a
#[1] 1

But it is better to have a named list instead of having multiple objects in the global environment i.e.

lst <- as.list(setNames(B, A))

The element can be extracted

lst[['a']]
#[1] 1

Upvotes: 2

Related Questions