Search code examples
rfunctionwhile-looplapply

Lappy with while function


I have a list of datasets, I need to change the variable names. Some characters (i.e. ".") are repeated. I want to get rid of them neatly combining a while loop and an aptly created function.

Both the function I wrote and the last line of code do not work. Any help welcome!

Minimal working example:

x <- data.frame("WRONG...." = "", "NOT.SO.WRONG." = "", "NOT.WRONG" = "")
myfiles <- list(x)


nopoints <- function(x){
  while (any(grepl('\\.\\.', names(x)))){
    setNames(x, sub('\\.\\.', '\\.', names(x)))}
  return(x)}

myfiles2 <- lapply(myfiles, nopoints)

myfile2 <- lapply(myfiles2, function(x) setNames(x, sub('\\.$', '', names(x))))

Desired result:

myfiles2 <- data.frame("WRONG" = "", "NOT.SO.WRONG" = "", "NOT.WRONG" = "")

Solution

  • Ok. The function was missing a key element

    nopoints <- function(x)
      {
      while (any(grepl('\\.\\.', names(x))))
        {
        x <- setNames(x, sub('\\.\\.', '\\.', names(x)))
      }
      return(x)
    }
    

    The second lapply call actually work as well on the example, it did not on my real list because of order of execution.