Reputation: 601
I have a data frame:
a <- c(1,2,3,4,5,6)
b <- c(1,2,1,2,1,4)
c <- c("A", "B", "C", "D", "E", "F")
df <- data.frame(a,b,c)
What I want to do, is create another vector d
, which contains the value of c
in the row of a
which matches each value of b
So my new vector would look like this:
d <- c("A", "B", "A", "B", "A", "D")
As an example, the final value of b
is 4
, which matches with the 4th row of a
, so the value of d
is the 4th row of c
, which is "D"
.
Upvotes: 2
Views: 46
Reputation: 20095
Another option is to convert to factor and use it as:
factor(a, labels = c)[b]
#[1] A B A B A D
OR
as.character(factor(a, labels = c)[b])
#[1] "A" "B" "A" "B" "A" "D"
data
a <- c(1,2,3,4,5,6)
b <- c(1,2,1,2,1,4)
c <- c("A", "B", "C", "D", "E", "F")
Upvotes: 0
Reputation: 2283
If a and b are both lists with integer values you can use them directly.
d <- c[b[a]]
d
[1] "A" "B" "A" "B" "A" "D"
if a is a regular integer sequence along c you can simply call c from b.
c[b]
[1] "A" "B" "A" "B" "A" "D"
Upvotes: 8