[R] remove text from nested list

Peter Langfelder peter@|@ng|e|der @end|ng |rom gm@||@com
Fri Oct 26 03:18:02 CEST 2018


You should be more specific about what you want to replace and with
what. The pattern you use, namely "[0-9][0-9]/[0-9[0-9].*com", does
not (AFAICS) match any of the strings in your data, so don't be
surprised that your commands do not change anything.

If you have a correct pattern and replacement and all lists have depth
3, using something like

lapply(mylist, lapply, lapply, function(y) gsub(pattern, replacement, y))

should work. If your list has a variable depth, I would use a
recursive function, something like

recursiveGSub = function(x, pattern, replacement)
{
  if (is.atomic(x)) gsub(pattern, replacement, x) else lapply(x,
recursiveGSub, pattern, replacement)
}

Example:

lst = list("a001", list("b001", list("c001", "d001")))

lst
recursiveGSub(lst, "00", "")


HTH,

Peter
On Thu, Oct 25, 2018 at 6:04 PM Ek Esawi <esawiek using gmail.com> wrote:
>
> Hi All—
>
> I have a list that contains multiple sub-lists and each sub-list
> contains multiple  sub(sub-lists), each of the sub(sub-lists) is made
> up of matrices of text. I want to replace some of the text in some
> parts in the matrices on the list. I tried gsub and stringr,
> str_remove, but nothing seems to work
>
> I tried:
>
> lapply(mylist, function(x) lapply(x, function(y)
> gsub("[0-9][0-9]/[0-9[0-9].*com","",y)))
> lapply(mylist, function(x) str_remove(x,"[0-9][0-9]/[0-9[0-9].*com"))
>
> Any help is greatly apprercaited.
>
>
>
> mylist—this is just an example
>
> [[1]]
> [[1]][[1]]
> [[1]][[1]][[1]]
> [,1]  [,2]  [,3]  [,4] [,5]
> [1,] "12/30 12/30"  "ABABABABABAB"  "8.00"
> [2,] "01/02 01/02"  "AAAAAAAAAAAA”.   “99"
> [3,] "01/02 01/02"  "CACACACACACC” "55.97"
>
> [[1]][[1]][[2]]
> [,1]  [,2]
> [1,] "12/30 12/30" "DDDDDDDDDDDDDDD” “29"
> [2,] "12/30 12/30"  :GGGGGGGGGGGGGGG” “333”
>
> [[1]][[2]]
> [[1]][[2]][[1]]
> [,1]  [,2]  [,3] [,4]  [,5]
> [1,]  "01/02 01/02" "ThankYou" “23”
> [2,] "01/02 01/02"  "Standard data"  "251"
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.




More information about the R-help mailing list