简体   繁体   中英

How to multiply columns in a dataframe (or matrix) by another dataframe's columns one by one and sum the results?

I am trying to multiply two data frames, x and y, identical rows number but different columns number. I need to multiply each column of x by each column of y.

I have tried several things and worked it out, but I need to make it automatic because now is kind of manually.

Example data:

>x
    a   b   c   d
Jan 2   4   8   6
Feb 5   8   3   6
Mar 4   8   2   3
Apr 4   4   5   6


>y
    e   f   g   h   j   k   l   m
Jan 5   6   8   7   2   3   4   6
Feb 2   5   7   9   6   3   4   5
Mar 9   2   5   5   5   3   2   1
Apr 2   7   5   4   1   2   3   5

In R,

    a1<-data.frame(a=colSums(data.frame(x[,1]*y[,1:8])))
    a1
    a2<-data.frame(b=colSums(data.frame(x[,2]*y[,1:8])))
    a2
    a3<-data.frame(c=colSums(data.frame(x[,1]*y[,1:8])))
    a3
    a4<-data.frame(d=colSums(data.frame(x[,2]*y[,1:8])))
    a4

The results expected is:

> a1
   a
e 64
f 73
g 91
h 95
j 58
k 41
l 48
m 61

> a2
    b
e 116
f 108
g 148
h 156
j 100
k  68
l  76
m  92
> a3
    c
e  74
f 102
g 120
h 113
j  49
k  49
l  63
m  90
> a4
    d
e  81
f 114
g 135
h 135
j  69
k  57
l  72
m  99

 a5<-data.frame(c(a1,a2,a3,a4))
  a   b   c   d
1 64 116  74  81
2 73 108 102 114
3 91 148 120 135
4 95 156 113 135
5 58 100  49  69
6 41  68  49  57
7 48  76  63  72
8 61  92  90  99

But I have a big dataset,so doing that for each column will take so much time, is there anyway to do it with a loop or for?

This is also matrix multiplication again:

mapply(`%*%`, x, list(as.matrix(y)))

mapply(crossprod, x, list(as.matrix(y)))

t(t(as.matrix(x)) %*% as.matrix(y))
#      a   b   c   d
#[1,] 64 116  74  81
#[2,] 73 108 102 114
#[3,] 91 148 120 135
#[4,] 95 156 113 135
#[5,] 58 100  49  69
#[6,] 41  68  49  57
#[7,] 48  76  63  72
#[8,] 61  92  90  99

You can use lapply() to loop through your data.frame columns.

A <- as.data.frame(lapply(x, function(x_1) colSums(x_1 * y[, 1:8])))
A

   a   b   c   d
e 64 116  74  81
f 73 108 102 114
g 91 148 120 135
h 95 156 113 135
j 58 100  49  69
k 41  68  49  57
l 48  76  63  72
m 61  92  90  99

Data

x <- read.table(text = 'a   b   c   d
Jan 2   4   8   6
Feb 5   8   3   6
Mar 4   8   2   3
Apr 4   4   5   6')


y <- read.table(text = '    e   f   g   h   j   k   l   m
Jan 5   6   8   7   2   3   4   6
Feb 2   5   7   9   6   3   4   5
Mar 9   2   5   5   5   3   2   1
Apr 2   7   5   4   1   2   3   5')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM