Hi Val, see 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
+ A, 0.25
+ B, 0.42
+ C, 0.65
",sep=",",header=TRUE,stringsAsFactors=F)>
> dat3 <- data.frame(ID = dat1[,1], Index = apply(dat1[,-1], 1, FUN=
function(x) {sum(x*dat2[,2])} ), stringsAsFactors=F)
> dat3
ID Index
1 A 24.58
2 B 35.59
3 C 17.10>
> str(dat3)
'data.frame': 3 obs. of 2 variables:
$ ID : chr "A" "B" "C"
$ Index: num 24.6 35.6 17.1>
The first two results "A" and "B" are identical to your
example, but
your math in "C" appears a little off.
HTH, Bill.
W. Michels, Ph.D.
On Sat, Sep 7, 2019 at 11:47 AM Val <valkremk at gmail.com>
wrote:>
> Hi All,
>
> I have two data frames with thousand rows and several columns. My
> samples of the data frames are shown below
>
> dat1 <-read.table(text="ID, x, y, z
> 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, x, y, z
> ID, weight
> A, 0.25
> B, 0.42
> C, 0.65 ",sep=",",header=TRUE,stringsAsFactors=F)
>
> My goal is to create an index value for each ID by mutliplying the
> first row of dat1 by the second column of dat2.
>
> (10*0.25 ) + (34*0.42) + (12*0.65)= 24.58
> (25*0.25 ) + (42*0.42) + (18*0.65)= 35.59
> (14*0.25 ) + (20*0.42) + ( 8*0.65)= 19.03
>
> The desired out put is
> dat3
> ID, Index
> A 24.58
> B 35.59
> C 19.03
>
> How do I do it in an efficent way?
>
> Thank you,
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.