R – How to do scalar multiply on data frame column

dataframer

I’m sure this one is sitting right in front of me but I can’t see it. I have a data frame, “a”, such that:

>a
         Chars    Numbers
This      A        15
That      B        22
Other     C        18

I simply want to multiply the Numbers column by a scalar, say b <- 10, and keep the other parts of the data frame intact. (I would get 150, 220, 180 in the Numbers column of the result, but the same row/column headings and Chars column.)

What does not work is a * b, trying to use apply, or a$Numbers * b.

Best Solution

Here are some options:

  • a$Numbers <- a$Numbers * b
  • transform(a, Numbers=Numbers * b)
  • within(a, Numbers <- Numbers * 10

In all cases you need to modify the data frame. The first method is the most direct, but the other two do similar things. For the second and third, you will need to save the result for it to be re-usable elsewhere (e.g. a <- transform(a, ...)).