obaqueiro
obaqueiro

Reputation: 982

Set value of a vector using a data-frame as "key","value" pair

I have two data frames DF1, DF2 each with 2 vectors DF1$A DF1$B, DF2$C, DF3$D. I need to sweep every row in DF1 and if the value in DF1$B equals some value in DF2$C then I need to show the corresponding value in DF2$D.

I have tried to solve this using ifelse and %in% without success. I cannot see why it does not work.

I have:

DataFrame1 (DF1)
A   B   
10  2
11  1
13  3
15  5
25  2
45  4

DataFrameB (DF2)
C D
1 A
2 B
3 C
4 D
5 E
6 F

What I do:

 DF1 <- data.frame(c(10, 11, 13, 15, 25, 45), c(2, 1, 3, 5, 2, 4))
 DF2 <- data.frame( c(1, 2,3,4,5,6), c("A", "B", "C", "D", "E", "F"))
 names(DF1) <-c("A","B")
 names(DF2) <-c("C", "D")
 ifelse((DF1$B %in% DF2$C), DF2$D, "NA")

What I get:

[1] 1 2 3 4 5 6

What I expected to get:

[1] B A C E B D

How can I achieve that?

Upvotes: 2

Views: 1938

Answers (2)

mdsumner
mdsumner

Reputation: 29525

I think what you really want is match():

DF2$D[match(DF1$B, DF2$C)]
[1] B A C E B D
Levels: A B C D E F

To simplify giving the columns names, you can do it when you create the data.frame. Also, to get characters instead of factor use stringsAsFactors:

DF1 <- data.frame(A = c(10, 11, 13, 15, 25, 45), B = c(2, 1, 3, 5, 2, 4))
DF2 <- data.frame(C = c(1, 2,3,4,5,6), D = c("A", "B", "C", "D", "E", "F"), stringsAsFactors = FALSE)

DF2$D[match(DF1$B, DF2$C)]

[1] "B" "A" "C" "E" "B" "D"

Upvotes: 5

Sacha Epskamp
Sacha Epskamp

Reputation: 47602

I think you need to use match() to get the indexes of DF1$B in DF2$C, then use that to index DF2$D:

DF2$D[match(DF1$B,DF2$C)]
[1] B A C E B D
Levels: A B C D E F

Is this what you mean?

Upvotes: 4

Related Questions