[R] Multiply

Val v@|kremk @end|ng |rom gm@||@com
Fri Aug 4 16:54:07 CEST 2023


Hi all,

I want to multiply two  data frames as shown below,

dat1 <-read.table(text="ID, x, y, z
 A, 10,  34, 12
 B, 25,  42, 18
 C, 14,  20,  8 ",sep=",",header=TRUE,stringsAsFactors=F)

dat2 <-read.table(text="ID, weight, weiht2
 A,  0.25, 0.35
 B,  0.42, 0.52
 C,  0.65, 0.75",sep=",",header=TRUE,stringsAsFactors=F)

Desired result

ID  Index1 Index2
1  A 24.58 30.18
2  B 35.59 44.09
3  C 17.10 21.30

Here is my attempt,  but did not work

dat3 <- data.frame(ID = dat1[,1], Index = apply(dat1[,-1], 1, FUN=
function(x) {sum(x*dat2[,2:ncol(dat2)])} ), stringsAsFactors=F)


Any help?

Thank you,



More information about the R-help mailing list