# Newbie alert # I am wanting to multiply the rows in a dataframe by a vector. # However, the default behavior appears to be for the vector to be applied # column wise. For example: vct <- 1:4 df <- data.frame(c1 = 5:10, c2= 6:11, c3=7:12, c4=8:13) multTheTwo <- vct * df multTheTwo # This results in the vector getting cycled columnwise # c1 c2 c3 c4 # 1 5 18 7 24 # 2 12 28 16 36 # 3 21 8 27 10 # 4 32 18 40 22 # 5 9 30 11 36 # 6 20 44 24 52 # But what I actually want is: # c1 c2 c3 c4 #1 5 12 21 32 which is 5*1, 6*2, 7*3, 8*4 #2 6 14 24 36 same pattern applied to the next row #3 7 16 27 40 so on .... #4 8 18 30 44 #5 9 20 33 48 #6 10 22 36 52 # I am currently using a for statement to do this, but that just doesn't feel # right. Is there another option that is more "R" like. for(i in 1:length(vct)) multTheTwo[,i] <- vct[i] * df[,i] multTheTwo # Thanks Richard --
Gabor Grothendieck
2006-Nov-14 00:16 UTC
[R] Question on applying vectors to data.frames by row
Here are a couple of possibilities: as.data.frame(t(t(df) * vct)) df * rep(vct, each = nrow(df)) On 11/13/06, RDM <rdmerrio at amaonline.com> wrote:> # Newbie alert > # I am wanting to multiply the rows in a dataframe by a vector. > # However, the default behavior appears to be for the vector to be applied > # column wise. For example: > > vct <- 1:4 > df <- data.frame(c1 = 5:10, c2= 6:11, c3=7:12, c4=8:13) > multTheTwo <- vct * df > multTheTwo > > # This results in the vector getting cycled columnwise > # c1 c2 c3 c4 > # 1 5 18 7 24 > # 2 12 28 16 36 > # 3 21 8 27 10 > # 4 32 18 40 22 > # 5 9 30 11 36 > # 6 20 44 24 52 > > # But what I actually want is: > # c1 c2 c3 c4 > #1 5 12 21 32 which is 5*1, 6*2, 7*3, 8*4 > #2 6 14 24 36 same pattern applied to the next row > #3 7 16 27 40 so on .... > #4 8 18 30 44 > #5 9 20 33 48 > #6 10 22 36 52 > > # I am currently using a for statement to do this, but that just doesn't > feel > # right. Is there another option that is more "R" like. > > for(i in 1:length(vct)) multTheTwo[,i] <- vct[i] * df[,i] > multTheTwo > > # Thanks Richard > > -- > > ______________________________________________ > 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. >
Seemingly Similar Threads
- Numerical Derivative / Numerical Differentiation of unknown funct ion
- modifying only certain rows in a data-frame
- Numerical Derivatives in R
- Numerical Derivative / Numerical Differentiation of unkno wn funct ion
- Unusual slowing of R matrix multiplication version 2.12.1 (2010-10-15) vs 2.12.0