I have a nested list in say lst(all the elements are of class int). I don’t know the length of lst in advance; however I do know that each element of lst is a list of length say k
length(lst[[i]]) # this equals k and is known in advance,
# this is true for i = 1 ... length(lst)
How do I take the union of the 1st element, 2nd element, …, kth element of all the elements of lst
Specifically, if the length of lst is n, I want (not R code):
# I know that union can only be taken for 2 elements,
# following is for illustration purposes
listUnion1 <- union(lst[[1, 1]], lst[[2, 1]], ..., lst[[n, 1]])
listUnion2 <- union(lst[[1, 2]], lst[[2, 2]], ..., lst[[n, 2]])
.
.
.
listUnionk <- union(lst[[1, k]], lst[[2, k]], ..., lst[[n, k]])
Any help or pointers are greatly appreciated.
Here is a dataset that can be used, n = 3 and k = 2
list(structure(list(a = 1:5, b = 6:11), .Names = c("a", "b")),
structure(list(a = 6:11, b = 1:5), .Names = c("a", "b")),
structure(list(a = 12, b = 12), .Names = c("a", "b")))
Here is a general solution, similar in spirit to that of @Ramnath, but avoiding the use of
union()which is a binary function. The trick is to note thatunion()is implemented as:and the bit inside
unique()can be achieved by unlisting thenth component of each list.The full solution then is:
which gives:
on the data you showed.
A couple of useful features of this are:
`[[`to subsetobjinunionFun. This is similar tofunction(x) x$ain @Ramnath’s Answer. However, we don’t need an anonymous function (we use`[[`instead). The equivalent to @Ramnath’s Answer is:lapply(lst, `[[`, 1)1above withninunionFun(), and allow our list to be passed in as argumentobj.Now that we have a function that will provide the union of the
nth elements of a given list, we canlapply()over the indicesk, applying ourunionFun()to each sub-element oflst, using the fact that the length oflst[[1]]is the same aslength(lst[[k]])for allk.If it helps to have the names of the
nth elements in the returned object, we can do: