I would like to add new columns to a dataframe, populated with predefined values stored in another dataframe. What is the best way to proceed?
Nice to have: is it possible to make the code dynamic in case new variables appear in d2?
d1 <- head(iris) # dataframe 1 ----------
var <- c("var1", "var2", "var3")
val <- c(5, 7, 1)
d2 <- as.data.frame(cbind(var, val)) # dataframe 2 ----------
First dataframe
Second dataframe
Desired output
Best regards
One way would be (this will work for any number of var
s)
d1[as.character(d2$var)] <- rep(d2$val, each = nrow(d1))
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species var1 var2 var3
# 1 5.1 3.5 1.4 0.2 setosa 5 7 1
# 2 4.9 3.0 1.4 0.2 setosa 5 7 1
# 3 4.7 3.2 1.3 0.2 setosa 5 7 1
# 4 4.6 3.1 1.5 0.2 setosa 5 7 1
# 5 5.0 3.6 1.4 0.2 setosa 5 7 1
# 6 5.4 3.9 1.7 0.4 setosa 5 7 1
Using data.table
:
require(data.table)
setDT(d1)[, as.character(d2$var) := as.list(d2$val)]
as.character()
is required because of the way you've created d2
, which resulted in var
being factor
.
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