2

I am stuck with a small problem while trying to clean my data. I have a property data set which has listing of property size as character. Most of the data for the size column is just numeric but in text format. If I convert them to numeric data, I will loose many data due to coercion. There are particular data where it is like (20*40)....which I am unable to convert. As this data is getting coerced to NA while conversion. Any guidance on how to handle this kind of issue?

NiMbuS
  • 87
  • 2
  • 9
  • Please consider to show a small erperoducible example and expectedd output – akrun May 16 '20 at 20:03
  • 1
    If the value is `20*40` do you need 800 as output? – akrun May 16 '20 at 20:14
  • If [this](https://stackoverflow.com/questions/24975229/in-r-evaluate-expressions-within-vector-of-strings) is what you want please say so and I will delete my answer below and close as duplicate. – Rui Barradas May 16 '20 at 20:19
  • I like all the Answers below, but is there any way to way to wrap the `eval` in something so that it can't get to frisky? Avoiding the 'Little Bobby Tables' (https://xkcd.com/327/) problem? – David T May 16 '20 at 20:41
  • @akrun - Yes....I want output value as 800.... – NiMbuS May 17 '20 at 08:58

3 Answers3

2

Maybe this function can be of help.

evalCell <- function(x){
  f <- function(x) eval(parse(text = x))
  sapply(x, f)
}

x <- c("(20*40)", 123, "1 + 2*3", "(1 + 2)*3")
evalCell(x)
#  (20*40)       123   1 + 2*3 (1 + 2)*3 
#      800       123         7         9 

If the return vector's names are not wanted, have the function return unname(sapply(etc)).

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
2

We can use map with parse_expr

library(purrr)
map_dbl(x, ~ eval(rlang::parse_expr(.x)))
#[1] 800 123   7   9

data

x <- c("(20*40)", 123, "1 + 2*3", "(1 + 2)*3")
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you for the solution....I tried it but it did not work. I am facing the below error... Error in parse(text = x) : :1:4: unexpected symbol 1: 25x75 ^ – NiMbuS May 17 '20 at 09:23
  • I think i got the issue....its not able to read 'x' as mathematical operation...thats the error is coming.... – NiMbuS May 17 '20 at 09:26
  • @NiMbuS it must be a package version issue as i can't reproduce it – akrun May 17 '20 at 18:47
0

You can try

sapply(yourColumn, function(X) eval(parse(text=X)))

Example:

> sapply(c("5+5", "22", "10*5"), function(X) eval(parse(text=X)) )
 5+5   22 10*5 
  10   22   50