Add two vectors by name
•
Java
I have two named vectors
v1 <- 1:4 v2 <- 3:5 names(v1) <- c("a","b","c","d") names(v2) <- c("c","e","d")
I want to add names to them, that is, the expected result is
> v3 a b c d e 1 2 6 9 4
Is there any way to do this programmatically in R? Note that the name may not necessarily be the sort order, such as v2. 0 above
Solution
Just combine the vectors (for example, use C) and use auto fill:
v3 <- c(v1,v2) tapply(v3,names(v3),sum) # a b c d e # 1 2 6 9 4
Or, for fun (because you're just doing summation), continue "V3":
xtabs(v3 ~ names(v3)) # names(v3) # a b c d e # 1 2 6 9 4
I think you can also use "data. Table":
library(data.table) as.data.table(Reduce(c,mget(ls(pattern = "v\\d"))),keep.rownames = TRUE)[,list(V2 = sum(V2)),by = V1] # V1 V2 # 1: a 1 # 2: b 2 # 3: c 6 # 4: d 9 # 5: e 4
(what I share is not "data. Table", but an automated way to capture vectors of interest.)
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码