I have a single list of numeric vector and I want to combine them into one vector. But I am unable to do that. This list can have one element common across the list element. Final vector should not add them twice. Here is an example:
>lst `1` [1] 1 2 `2` [2] 2 4 5 `3` [3] 5 9 1
I want final result as this
>result [1] 1 2 4 5 9 1
I tried doing following things, without worrying about the repition:
>vec<-vector() >sapply(lst, append,vec)
and
>vec<-vector() >sapply(lst, c, vec)
None of them worked. Can someone help me on this?
Thanks.
To convert List to Vector in R, use the unlist() function. The unlist() function simplifies to produce a vector by preserving all atomic components.
The concatenation of vectors can be done by using combination function c. For example, if we have three vectors x, y, z then the concatenation of these vectors can be done as c(x,y,z).
combine. lists is an R function developped combine/append two lists, with special attention to dimensions present in both. combine. lists(list1, list2) returns a list consisting in the elements found in either list1 or list2, giving precedence to values found in list2 for dimensions found in both lists.
Converting a List to Vector in R Language – unlist() Function. unlist() function in R Language is used to convert a list to vector. It simplifies to produce a vector by preserving all components.
You can use the c () function in R to combine two or more vectors into a single vector. Pass the vectors you want to combine as comma-separated arguments to the c () function. The following is the syntax – c(vec1, vec2, vec3, ...) It returns a single combined vector. Let’s look at some examples of combining vectors.
List2 contains a single vector comprising of real numbers. Merged List is of size three as a summation of all these three vectors. How to Convert matrix to a list of column vectors in R ?
Vectors are a sequence of elements belonging to the same data type. A list in R, however, comprises of elements, vectors, variables or lists which may belong to different data types.
It returns a single combined vector. Let’s look at some examples of combining vectors. Let’s combine two numeric vectors together into a single vector. First, we will use the c () function to create the individual vectors and then use the c () again to combine the vectors together.
A solution that is faster than the one proposed above:
vec<-unlist(lst) vec[which(c(1,diff(vec)) != 0)]
Another answer using Reduce()
.
Create the list of vectors:
lst <- list(c(1,2),c(2,4,5),c(5,9,1))
Combine them into one vector
vec <- Reduce(c,lst) vec # [1] 1 2 2 4 5 5 9 1
Keep the repeated ones only once:
unique(Reduce(c,lst)) #[1] 1 2 4 5 9
If you want to keep that repeated one at the end, You might want to use vec[which(c(1,diff(vec)) != 0)]
as in @Rachid's answer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With