Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add columns with predefined values to a dataframe

Tags:

r

dplyr

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?

data for reproducible code

d1 <- head(iris)                      # dataframe 1 ----------

var <- c("var1", "var2", "var3")
val <- c(5, 7, 1)
d2 <- as.data.frame(cbind(var, val))  # dataframe 2 ----------

Expected output

First dataframe

enter image description here

Second dataframe

enter image description here

Desired output

enter image description here

Best regards

like image 563
cho7tom Avatar asked Dec 24 '22 18:12

cho7tom


2 Answers

One way would be (this will work for any number of vars)

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
like image 79
David Arenburg Avatar answered Jan 04 '23 23:01

David Arenburg


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.

like image 41
Arun Avatar answered Jan 04 '23 23:01

Arun