Most solutions I found were for data frames or lists, not for vectors.
From:
myvec = c(A=2, B=2, A=2)
To:
desiredvec = c(A=4, B=2)
You can use tapply
> tapply(myvec, names(myvec), sum)
A B
4 2
or xtabs
> xtabs(myvec~names(myvec))
names(myvec)
A B
4 2
You can use rowsum
:
rowsum(myvec, names(myvec))
# [,1]
#A 4
#B 2
rowsum
returns a matrix. If you need a vector.
rowsum(myvec, names(myvec))[, 1]
#A B
#4 2
splitbyitsnames <- function(namedVec) { # split a list by its names
stopif(is.null(names(namedVec)), message = "NO NAMES")
split(namedVec, f = names(namedVec))
}
unlapply <- function (...) { unlist(lapply(...)) } # lapply, then unlist
sumBySameName <- function(namedVec) { # Sum up vector elements with the same name
unlapply(splitbyitsnames(namedVec), sum)
}
From CodeAndRoll
> sumBySameName(myvec)
A B
4 2
Please add if there is a better solution