[R] multiplying values in data frame by corresponding value in the first column

Marc Schwartz marc_schwartz at me.com
Tue Sep 21 22:24:30 CEST 2010


On Sep 21, 2010, at 3:00 PM, Martin Tomko wrote:

> I am sure there is a simple solution to this... I have a column in a data frame specifying a grouping (1, -1) for my observations, and need to mutliply each observation in all the other columns of the data frame by the corresponding value in the given column. I played with apply, and saw some suggestions for sweep, but did not manage to get it working.
> 
> My table contains NAs....
> 
> Example of table as data frame
> Observation Group Param1 Param2
> AA                1        3        4
> BB                -1        5        6
> 
> 
> Expected result:
> Observation Group Param1 Param2
> AA                1        3        4
> BB                -1        -5        -6
> 
> group<-as.vector(table$Group)
> I extracted the first column into a vector, and am looking for a way to multiply each of the columns... SO far, only manual solutions (uglyyyy) work: table$Param1<-group*table$Param1
> 
> Thanks many times!
> Martin


One approach is to use ?transform:

> DF
  Observation Group Param1 Param2
1          AA     1      3      4
2          BB    -1      5      6


> transform(DF, Param1 = Param1 * Group, Param2 = Param2 * Group)
  Observation Group Param1 Param2
1          AA     1      3      4
2          BB    -1     -5     -6


However, that is likely to get tedious with a large number of columns to the right of 'Group', presuming that your actual data may be wider than the above example. Thus, another approach may be:

DF[, -c(1:2)] <- DF[, -c(1:2)] * DF$Group

> DF
  Observation Group Param1 Param2
1          AA     1      3      4
2          BB    -1     -5     -6


HTH,

Marc Schwartz



More information about the R-help mailing list