3

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)

4 Answers 4

5

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
1

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 
0

Define:

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

Call:

> sumBySameName(myvec)
A B 
4 2 

Please add if there is a better solution


0

Using aggregate/stack

aggregate(values ~ ., stack(myvec), sum)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.