'Replacing in list inside list in R
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??
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ThomasIsCoding |
