Search code examples
rdataframedivide

R Divide all rows of a dataframe column by a number


I am trying to divide all rows of my dataframe column by a number (say 10). I thought it to be a trivial problem until I tried it. In the example below, I am trying to get the 'mm' column to result in values 8100, 3222.2 and 5433.3

test <- data.frame(locations=c("81000","32222","54333"), value=c(87,54,43))
test$mm <- as.numeric(test$locations) / 10
head(test)
     locations value  mm
   1     81000    87 0.3
   2     32222    54 0.1
   3     54333    43 0.2

What am I doing wrong?


Solution

  • Change factors to be character, then apply as.numeric

    > test$mm <- as.numeric(as.character(test$locations)) / 10
    > test
      locations value     mm
    1     81000    87 8100.0
    2     32222    54 3222.2
    3     54333    43 5433.3