Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign a value to a df$column from another df?

Tags:

r

Example: I have a df in which the first column is

dat <- c("A","B","C","A")

and then I have another df in which I have in the first column is:

dat2[, 1]
[1] A B C
Levels: A B C

dat2[, 2]
[1] 21000 23400 26800

How can I add the values in the second df (dat2) to the first df (dat)? In the first df there are repetitions and I want that everytime there is an "A" it will add the corresponding value (21000) from the second df in a new column.

like image 618
Mike JJ Avatar asked Sep 05 '17 22:09

Mike JJ


1 Answers

Generating reproducible dataframe...

dat1 <- data.frame(x1 = c("A","B","C","A"), stringsAsFactors = FALSE)
dat2 <- data.frame(x1 = c("A","B","C"),
                   x2 = c(21000, 23400, 26800), stringsAsFactors = FALSE)

Then use the match function.

dat1$dat2_vals <- dat2$x2[match(dat1$x1, dat2$x1)]

It is important to transform your character columns to character type rather than factor type or the elements will not match. I mention this due to the levels attribute in your dat2.

like image 194
D.sen Avatar answered Sep 20 '22 13:09

D.sen