Angelos Amyntas
Angelos Amyntas

Reputation: 181

Multiply all values in each column of a data frame by another value based on matching column names

I would like to find an efficient way to multiply all values in each column in this data-frame

dd <- data.frame(a=1:10,b=2:11,c=3:12)

with a value that corresponds to the name of that column on another "index" data-frame (like in either of the examples below)

d.1 <- data.frame(p=c("a","b","c"),q=3:5)
d.2 <- data.frame(a=3,b=4,c=5)

Is there a for loop way to achieve this?

Upvotes: 1

Views: 493

Answers (2)

Javier
Javier

Reputation: 457

I provide you a for loop-like strategy for both cases: Using d.1:

dd_new <- vector()

for(i in 1:length(dd)){
  new_col <- dd[, i] * d.1$q[which(d.1$p==names(dd)[i])]
  dd_new <- as.data.frame(cbind(dd_new, new_col))
}
dd_new

Using d.2:

dd_new <- vector()

for(i in 1:length(dd)){
  new_col <- dd[, i] * d.2[, which(names(d.2)==names(dd)[i])]
  dd_new <- as.data.frame(cbind(dd_new, new_col))
}
dd_new

Upvotes: 1

akrun
akrun

Reputation: 887118

We can replicate the second dataset and do the multiplication if we use the 'd.2'

dd[names(d.2)] <-  dd[names(d.2)] * d.2[col(dd[names(d.2)])]

With 'd.1'

dd[as.character(d.1$p)] <-  dd[as.character(d.1$p)] * d.1$q[col(dd[d.1$p])]

Upvotes: 1

Related Questions