ToNoY
ToNoY

Reputation: 1378

Multiplying two different dataframes only for completely matching row and column names

Lets make a dummy data first

a=data.frame(average=c(5,6), row.names=c("Q", "R"))
> a
  average
Q       5
R       6

b=data.frame(c(5,5,7), c(8,9,10), c(11,12,14))
> colnames(b)<-c("Q","QQ","R")
> b
  Q QQ  R
1 5  8 11
2 5  9 12
3 7 10 14

i want to multiply columns of 'b' that completely match with the row names of 'a' (here, Q and R completely match). But when I make a simple loop it gives

n = row.names(a)
> lapply(1:length(n), function(i)
+ a[grep(n[i], row.names(a)),]*b[,grep(n[i], colnames(b))])
[[1]]
   Q QQ
1 25 40
2 25 45
3 35 50

[[2]]
[1] 66 72 84

which means it also multiplies QQ since Q and QQ have one letter in common! How can I get the following?

[[1]]
[1] 25 25 35

[[2]]
[1] 66 72 84

Upvotes: 1

Views: 920

Answers (1)

flodel
flodel

Reputation: 89097

When you want column "Q" of a data.frame, you can just do b[, "Q"] or b[["Q"]]. Whereas doing b[, grep("Q", colnames(b))] will return all columns whose name contains a Q. With that in mind, your code should be:

n <- rownames(a)
lapply(1:length(n), function(i) a[n[i], ] * b[, n[i]])

or

lapply(rownames(a), function(i) a[i, ] * b[, i])

Maybe a more elegant approach would be to do:

i <- intersect(rownames(a), colnames(b))
Map(`*`, a[i, ], b[, i])

Upvotes: 2

Related Questions