2 Numeric Values In A Dataframe Field

Hi Folks,

Maybe a basic one.

Basically, I am cleaning a csv file that I have imported through R Studio.

Several of the columns have combined numeric values such as below

72+3
58+3
87+3
74+3
86+5
86+3
70+1
85+2
80+4
81+4

Is there some code that I can use to update the field to be the sum of the 2 numbers?

Thanks,
Mark

Hello Mark,

cool question actually and yes it works.

Let's create a demo-dataset first:

library(tidyverse)
dataframe = tibble(ID = LETTERS[1:9],
                   value = c("72+3", "58+3", "43",
                             "87+3", "74+3", "65", 
                             "86+5", "86+3", "70+1"))

Then you can convert the values into something taht is called expression, and this can then be evaluated, in other words the calculation is performed.

new_dataframe = dataframe %>%
  rowwise() %>%
  mutate(new_value = eval(parse(text = value)))

Here a new dataframe is created and in that a new column ("new_value") you can also overwrite the existing column by inserting this line in the code above:
mutate(value = eval(parse(text = value)))

Matthias

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.