Home > Software design >  Replacing in list inside list in R
Replacing in list inside list in R

Time:03-02

I have a list of lists like the following:

x <- list(x = list(a = 1:10, b = 10:20), y = 4, z = list(a = 1, b = 2))

str(x)

List of 3
 $ x:List of 2
  ..$ a: int [1:10] 1 2 3 4 5 6 7 8 9 10
  ..$ b: int [1:11] 10 11 12 13 14 15 16 17 18 19 ...
 $ y: num 4
 $ z:List of 2
  ..$ a: num 1
  ..$ b: num 2

How can I replace values in the list "a" inside list "x" (x$a) to replace for example the 1 with 100.

My real data is very large so I cannot do it one by one and the unlist function is not a solution for me because I miss information.

Any ideas??

CodePudding user response:

Operate on all a subcomponents

For the list x shown in the question we can check whether each component is a list with an a component and if so then replace 1 in the a component with 100.

f <- function(z) { if (is.list(z) && "a" %in% names(z)) z$a[z$a == 1] <- 100; z }
lapply(x, f)

Just x component

1) If you only want to perform the replacement in the x component of x then x2 is the result.

x2 <- x
x2$x$a[x2$x$a == 1] <- 100

2) Another possibility for the operating on just the x component is to use rrapply.

library(rrapply)

cond <- function(z, .xparents) identical(.xparents, c("x", "a"))
rrapply(x, cond, function(z) replace(z, z == 1, 100))

3) And another possibility is to use modifyList

modifyList(x, list(x = list(a = replace(x$x$a, x$x$a ==1, 100))))

4) within is another option.

within(x, {  x$a[x$a == 1] <- 100 })

CodePudding user response:

Here is trick using relist unlist

> v <- unlist(x)

> relist(replace(v, grepl("\\.a\\d?", names(v)) & v == 1, 100), x)
$x
$x$a
 [1] 100   2   3   4   5   6   7   8   9  10

$x$b
 [1] 10 11 12 13 14 15 16 17 18 19 20


$y
[1] 4

$z
$z$a
[1] 100

$z$b
[1] 2
  • Related