[R] How to multiply all dataframe rows by another dataframe's columns
Moshe Olshansky
m_olshansky at yahoo.com
Thu Aug 30 03:55:27 CEST 2007
Below is one way to do this:
> Loc1.alleles <- c(1,5,6,7,8)
> Loc1.Freq <- c(0.35, 0.15, 0.05, 0.10, 0.35)
> Loc1 <- cbind( Loc1.alleles,Loc1.Freq)
> X <- data.frame(Loc1)
> Loc2.alleles <- c(1,4,6,8)
> Loc2.Freq <- c(0.35, 0.35, 0.10, 0.20)
> Loc2 <- cbind(Loc2.alleles, Loc2.Freq)
> Y <- data.frame (Loc2)
>
> Z<-Y[,2] %o% X[,2]
> Z
[,1] [,2] [,3] [,4] [,5]
[1,] 0.1225 0.0525 0.0175 0.035 0.1225
[2,] 0.1225 0.0525 0.0175 0.035 0.1225
[3,] 0.0350 0.0150 0.0050 0.010 0.0350
[4,] 0.0700 0.0300 0.0100 0.020 0.0700
> dim(Z) <- c(prod(dim(Z)),1)
> Z
[,1]
[1,] 0.1225
[2,] 0.1225
[3,] 0.0350
[4,] 0.0700
[5,] 0.0525
[6,] 0.0525
[7,] 0.0150
[8,] 0.0300
[9,] 0.0175
[10,] 0.0175
[11,] 0.0050
[12,] 0.0100
[13,] 0.0350
[14,] 0.0350
[15,] 0.0100
[16,] 0.0200
[17,] 0.1225
[18,] 0.1225
[19,] 0.0350
[20,] 0.0700
>
Regards,
Moshe.
--- Luke Neraas <lukasneraas at gmail.com> wrote:
> Hello,
>
> I have two data frames, X and Y, with two columns
> each and different numbers
> of rows.
>
> # creation of data frame X
>
> Loc1.alleles <- c(1,5,6,7,8)
> Loc1.Freq <- c(0.35, 0.15, 0.05, 0.10, 0.35)
> Loc1 <- cbind( Loc1.alleles,Loc1.Freq)
> X <- data.frame(Loc1)
>
> #creation of data frame Y
>
> Loc2.alleles <- c(1,4,6,8)
> Loc2.Freq <- c(0.35, 0.35, 0.10, 0.20)
> Loc2 <- cbind(Loc2.alleles, Loc2.Freq)
> Y <- data.frame (Loc2)
>
> I would like a flexible way to multiply each element
> of second column of the
> X data frame
> by each element of the second column of the Y data
> frame.
>
> example of what the operation need to do:
> X[1,2]*Y[,2] ;
> X[2,2]*Y[,2].............X[4,2]*Y[,2]
>
> I have worked on a variety of "for" loops to get
> this to work without
> success.
>
> The final result should look like a column like this
>
> "all_X[,2] * all_Y[,2]"
> 0.1225
> 0.1225
> 0.0350
> 0.0700
> 0.0525
> 0.0525
> 0.0150
> 0.0300
> 0.0175
> 0.0175
> 0.0050
> 0.0100
> 0.0350
> 0.0100
> 0.0200
> 0.1225
> 0.1225
> 0.0350
> 0.0700
>
> any help would be greatly appreciated
>
> Luke Neraas
>
> lukasneraas at gmail.com
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> 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.
>
More information about the R-help
mailing list