1

I am trying to use lapply to replace the elements of a string in several data.frames contained in a list. When I attempt to do this, the whole data.frame is replaced, rather than the string contained in the data.frame.

A reproducible example below:

a <- list( a  = data.frame(Date = c("1900-08-31"), Val = 1000),
           b  = data.frame(Date = c("1900-08-31"), Val = 1000) )

lapply(a, function(x){

    gsub(".{2}$","01",x$Date)


})

What I would expect to happen is the elements of a$Date and b$Date get replaced with '1900-08-01'. But what happens is a and b get replaced with "1900-08-01"

Adam_123
  • 159
  • 9

1 Answers1

3

Your lapply function is returning a vector with the replacement instead of a and b with Date modified. Try this:


lapply(a, function(x){

    x$Date <- gsub(".{2}$","01",x$Date)

    return(x)
})

JdeMello
  • 1,708
  • 15
  • 23