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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With