daily pastebin goal
16%
SHARE
TWEET

Untitled

a guest Aug 11th, 2018 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Check if character value is a valid R object name
  2. "^[.[:alpha:]][._[:alnum:]]*$"
  3.    
  4. isValidAndUnreserved <- function(string) {
  5.     make.names(string) == string
  6. }
  7.  
  8. isValidAndUnreserved(".jjj")
  9. # [1] TRUE
  10. isValidAndUnreserved(" jjj")
  11. # [1] FALSE
  12.    
  13. isValidName <- function(string) {
  14.     grepl("^[.[:alpha:]][._ [:alnum:]]*$", string)
  15. }
  16.  
  17. isValidAndUnreservedName <- function(string) {
  18.     make.names(string) == string
  19. }
  20.  
  21. testValidity <- function(string) {
  22.     valid <- isValidName(string)
  23.     unreserved <- isValidAndUnreservedName(string)
  24.     reserved <- (valid & ! unreserved)
  25.     list("Valid"=valid,
  26.          "Unreserved"=unreserved,
  27.          "Reserved"=reserved)
  28. }
  29.  
  30. testNames <- c("mean", ".j_j", "...", "if", "while", "_jj", "  j")
  31. t(sapply(testNames, testValidity))
  32.  
  33.       Valid Unreserved Reserved
  34. mean  TRUE  TRUE       FALSE  
  35. .j_j  TRUE  TRUE       FALSE  
  36. ...   TRUE  TRUE       FALSE  
  37. if    TRUE  FALSE      TRUE    
  38. while TRUE  FALSE      TRUE    
  39. _jj   FALSE FALSE      FALSE  
  40.   j   FALSE FALSE      FALSE  # These tests for "  j", not "j"
  41.    
  42. make.names(".x")   # ".x"
  43. make.names("_x")   # "X_x"
  44. make.names("if")   # " if."
  45. make.names("function")  # "function."
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top