[R] Question on applying vectors to data.frames by row
RDM
rdmerrio at amaonline.com
Tue Nov 14 04:08:29 CET 2006
Thanks, both of these choices are much better than mine. I appreciate your
time.
Richard
-----Original Message-----
From: Gabor Grothendieck [mailto:ggrothendieck at gmail.com]
Sent: Monday, November 13, 2006 6:16 PM
To: RDM
Cc: r-help at stat.math.ethz.ch
Subject: Re: [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.
>
--
No virus found in this incoming message.
1:40 PM
--
1:40 PM
More information about the R-help
mailing list