Reputation: 421
I'm trying to use the named index to replace some elements of a list.
I have three lists:
My objective is to replace the old elements in Superset with the corresponding ones from Subset where Name(Subset) == Name(Superset).
Example Code (Edited for correctness):
# Setting things up
Superset <- list(1, 2, 3, 4)
names(Superset) <- c("a", "b", "c", "d")
Subset <- list(5, 6)
names(Subset) <- c("b", "c") # or any names from Superset
SubsetNames <- as.list(names(Subset))
I have tried things like this:
lapply(SubsetNames, FUN=function(x) Superset[[x]] <- Subset[[x]])
And:
Superset[SubsetNames] <- Subset
I even tried to construct a for-loop with a counter however this is not a working solution in my scenario.
In reality, Superset is a list of dataframes, each of which has almost 90k datapoints in 117 columns. Some of those dataframes need some tweaking. I have code which successfully extracts a list of the ones needing tweaking and tweaks them... now I just need to put them back.
Your help much appreciated! Thank you!
Upvotes: 3
Views: 1071
Reputation: 887213
We can use the names
of the 'Subset' to subset the 'Superset' and assign it to values of 'Subset'
Superset[names(Subset)] <- Subset
Superset
#$a
#[1] 1
#$b
#[1] 5
#$c
#[1] 6
#$d
#[1] 4
The list
creation seems to be faulty. It would be as.list
Superset <- as.list(1:4)
It will return a list
of length
4 as opposed to length
1 with list(1:4)
Upvotes: 2
Reputation: 206253
If you want to change for every value in Subset, you could just do
modifyList(Superset, Subset)
or if you are just updating a smaller set of values from subset
modifyList(Superset, Subset[SubsetNames])
Upvotes: 1