0

I have the following code that I use to uniform the names into a dataframe (tb):

names(tb) = tolower(names(tb))
names(tb) = gsub("\\:", "", names(tb))
names(tb) = gsub("\\.", "_", names(tb))
names(tb) = gsub("\\-", "_", names(tb))
names(tb) = gsub("[[:space:]+]", "_", names(tb))

I need to apply those 5 strings to multiple dataframes, so I'd like to create a function for this. Can you help me please? Thanks!

2
  • Is there any specific reason you want to build your own function? Have you tried the function clean_names() from the package janitor? Commented Mar 13, 2019 at 17:47
  • We could make it more simple with chartr("[.- ]", "---", gsub(":", "", tolower(names(tb))))) Commented Mar 13, 2019 at 17:47

2 Answers 2

1

Pretty simple, just pass your dataframe to the function, change the names and then return the changed dataframe.

name_change <- function(tb) {

names(tb) = tolower(names(tb))
names(tb) = gsub("\\:", "", names(tb))
names(tb) = gsub("\\.", "_", names(tb))
names(tb) = gsub("\\-", "_", names(tb))
names(tb) = gsub("[[:space:]+]", "_", names(tb))
return tb

}
Sign up to request clarification or add additional context in comments.

2 Comments

This is pretty hard-coded and might be less efficient.
@NelsonGon it's not hardcoded at all? It takes the names of a dataframe.
1

It can be simplified in a function with

f1 <- function(v1) {
     gsub("[. -]+", "_", gsub(":", "", tolower(v1)))
  }

or using chartr

f2 <- function(v1) {
    chartr(". -", "___", gsub(":", "", tolower(v1)))
 }

f1(str1)
#[1] "hellos1_s2_s3_s4"

f2(str1)
#[1] "hellos1_s2_s3_s4"

data

str1 <- "hello:s1.s2-s3 s4"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.