Merge two vectors

The objective is to merge two named vectors and if some variables have common name, only one is used.
It is similar is modifyList() but applied to vector. The trick is to convert vectors as lists, and unlist them at the end to return vectors:
unlist(modifyList(as.list(A), as.list(B)))

> A <- c(K=1, L=2)
> B <- c(X=3, Y=0, Z=2)
> # No common name, it makes just a concatenation 
> unlist(modifyList(as.list(A), as.list(B)))
K L X Y Z 
1 2 3 0 2 
> A <- c(K=1, L=2, X=10)
> # X is common, only the second one is used
> unlist(modifyList(as.list(A), as.list(B)))
K L X Y Z 
1 2 3 0 2 
> B <- NULL
> # If one is NULL, just return the first one
> unlist(modifyList(as.list(A), as.list(B)))
K  L  X 
1  2 10 
> B <- c(X=3, Y=0, Z=2)
> A <- NULL
> unlist(modifyList(as.list(A), as.list(B)))
X Y Z 
3 0 2

This trick has been introduced as a function modifyVector() in the packages HelpersMG():

modifyVector {HelpersMG}
R Documentation
Modifies Elements of a Vector
Description
Modifies a vector by changing a subset of elements to match a second vector.
Usage
modifyVector(x, val)
Arguments
x
A named vector.
val
A named vector with components to replace corresponding components in x.
Details
modifyVector modifies elements of a vector
Value
A modified version of x, with the elements of val replacing the elements of x
Author(s)
Marc Girondot
Examples
library("HelpersMG")
e <- c(M=10, L=20, J=30)
modifyVector(e, c(U=10, M=30))

[Package HelpersMG version 1.3.3 Index]

Commentaires

Posts les plus consultés de ce blog

Standard error from Hessian Matrix... what can be done when problem occurs

stepAIC from package MASS with AICc

Install treemix in ubuntu 20.04