Re: [R] substitute "x" for "pattern" in a list, while preservign list "structure". lapply, gsub, list...?

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Wed, 16 May 2007 14:22:10 -0400

Here is a recursive function you could try. Here f has been defined only to convert character variables. Modify to suit.

recurse <- function(x, f) {

   if (length(x) == 0) return(x)
   if (is.list(x)) for(i in seq_along(x)) x[[i]] <- recurse(x[[i]], f)    else x <- f(x)
   x
}
f <- function(x) if (mode(x) == "character") gsub("red", "green", x) else x list4 <- recurse(list1, f)

On 5/16/07, new ruser <newruser_at_yahoo.com> wrote:
> I am experimenting with some of the common r functions.
> I had a question re:using "gsub" (or some similar functions) on the contents of a list.
>
> I want to design a function that looks at "everything" contained din a list, and anytime it finds the text string "pattern" replace it with "x". I also wish to preserve the "structure" of the original list. What is a good way to accomplish this?
>
> I tried :
>
> a = matrix(data=c(23,45,'red',78),nrow=2)
> b = c('red','green',1,2,3)
> d = data.frame( test1=c(223,445,'red',78,56) , test2= c('red',NA,NA,NA,NA) )
> e= list(a,b,d)
> list1 = list(a,b,d,e)
>
> list2 = lapply(list1,function(list)(gsub("red","green",list)))
>
> str(list1)
> str(list2)
>
> but the structue fo the list changed.
>
>
> ---------------------------------
> Give spam the boot. Take control with tough spam protection
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help_at_stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



R-help_at_stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Wed 16 May 2007 - 18:30:14 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 16 May 2007 - 18:31:05 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.