2

I am automating a R code for which I have to use make.names function. Default behavior of make.names function is fine with me but when my table name contains a "-", I want the table name to be different.

For example, current behavior :

  > make.names("iris-ir")
    [1] "iris.ir"

But I want it to modify only in the case when I have "-" present in table name:

    > make.names("iris-ir")
    [1] "iris_ir"

How can I achieve this? EDIT: using only builtin packages.

smci
  • 32,567
  • 20
  • 113
  • 146
HiveRLearner
  • 107
  • 2
  • 10

1 Answers1

3

Use the following function:

library(dplyr)
make_names<-function(name)
  {
    name <- as.character(name)
    if(contains("-", vars = name))
       sub("-", "_", name)
  }

This should do what you want. Sorry, I forgot to mention that the contains function is in the dplyr package.

Without dplyr

make_names<-function(name)
  {
    name <- as.character(name)
    if(grepl("-", name, fixed = T))
       sub("-", "_", name)
    else
       name
  }
sanyi14ka
  • 809
  • 9
  • 14
  • `contains` is not a base R function afaik. When using packages, you should make that clear by loading them. – talat May 04 '17 at 07:46
  • Unfortunately I can not use dplyr package. I am automating some code of open source which can only use core packages – HiveRLearner May 04 '17 at 07:53
  • 2
    @HiveRLearner: then you need to state that requirement in your question – smci Jun 26 '18 at 23:59