I am trying to set up a table where the users can insert formulas in the form of a string.
They are allowed to use only operators and given par names (eg, par.names<- c("P1", "P2", "P3") )
I need to test if the formula is correct, by checking whether a user has used any other patterns.
For example P1+P2*P3 should be acceptable, while P1+P5*P$4 should return an error.
What would be the suggested way to do this?
Thank you!
Maybe you can try the code below
all(unlist(strsplit(s,"[^[:alnum:]]")) %in% par.names)
Example
> s1 <- "P1+P2*P3"
> s2 <- "P1+P5*P$4"
> all(unlist(strsplit(s1,"[^[:alnum:]]")) %in% par.names)
[1] TRUE
> all(unlist(strsplit(s2,"[^[:alnum:]]")) %in% par.names)
[1] FALSE
create a vector which holds strings of valid characters:
Allowed = c("+","-","*", "/","P","n","X")
write a function to check if any of the characters in the command are not allowed:
Vcheck = function(string){
temp = strsplit(string, "")
(((temp %in% Allowed) %>% sum) == length(temp)) %>% return
}
This should return 1 if it contains allowed character, and 0 if it contains a forbidden one. I trust you know how to write a function to return an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With