Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R- Check if string contains only certain patterns

Tags:

r

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!

like image 366
tzema Avatar asked Jun 09 '26 17:06

tzema


2 Answers

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
like image 162
ThomasIsCoding Avatar answered Jun 11 '26 09:06

ThomasIsCoding


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.

like image 43
dvd280 Avatar answered Jun 11 '26 08:06

dvd280