Search code examples
rdataframeadditioncoercion

R - Adding numbers within a data frame cell together


I have a data frame in which the values are stored as characters. However, many values contain two numbers that need to be added together. Example:

                    2014 Q1 Sales   2014 Q2 Sales   2014 Q3 Sales   2014 Q4 Sales 
  Product 1                  3+6            2+10               8            13+2
  Product 2                    6             4+0            <NA>               5
  Product 3                 <NA>             5+9             3+1              11

Is there a way to go through the whole data frame and replace all cells containing characters like "3+6" with new values equal to their sum? I assume this would involve coercing the characters to numeric or integers, but I don't know how that would be possible for values with the + sign in them. I would like the example data frame to end up looking like this:

                    2014 Q1 Sales   2014 Q2 Sales   2014 Q3 Sales   2014 Q4 Sales 
  Product 1                    9              12               8              15
  Product 2                    6               4            <NA>               5
  Product 3                 <NA>              14               4              11

Solution

  • Here's an easier example:

    dat <- data.frame(a=c("3+6", "10"), b=c("12", NA), c=c("3+4", "5+6"))
    dat
    ##      a    b   c
    ##  1 3+6   12 3+4
    ##  2  10 <NA> 5+6
    
    apply(dat, 1:2, function(x) eval(parse(text=x)))
    ##       a  b  c
    ## [1,]  9 12  7
    ## [2,] 10 NA 11
    

    Using R itself to do the computation with eval and parse does the trick.