Home > Enterprise >  Merge named vectors in different sizes into data frame
Merge named vectors in different sizes into data frame

Time:10-15

I have some different named vectors, and I want to combine them into one date frame that sums the actions.

 adjust balance   drive    idle   other    pick putdown replace    sort    wait 
      4       9      16      82       4     350      61      16      26      18 
   walk 
     14 

 adjust balance   drive    idle    pick putdown replace    sort  unload    walk 
      1      42      14      47     385     118       4      83      19       7 

i want it to be this way:

 adjust balance   drive  
      5       51      30  

and etc..

i find it very challenging because those are named vectors would be grateful for your help, thank you!

CodePudding user response:

We can use aggregate stack like below

aggregate(. ~ ind, rbind(stack(vec1), stack(vec2)), sum)

CodePudding user response:

You could convert to a data.frame and use the dplyr package to group by the names and sum the numbers together.

library(dplyr)
vec <- c(4, 9, 16, 1, 42, 14)
names(vec) <- c("adjust", "balance", "drive", "adjust", "balance", "drive")
data.frame(values = vec, name = names(vec)) %>% group_by(name) %>% summarise(values = sum(values))

CodePudding user response:

If we want to add all elements that match between the two vectors:

# Resolve the matching names of the vectors:
# vec_nm_order => character vector
vec_nm_order <- intersect(
   names(vec1),
   names(vec2)
)

# Add the related scalars together:
# named integer vector => stdout(console)
vec1[vec_nm_order]   vec2[vec_nm_order]

If we only want to add values for adjust, balance, drive:

# Choose the names (keys) of elements we want to add together:
# vec_nm_order => character vector
vec_nm_order <- c(
   "adjust", "balance", "drive"
)

# Add the related scalars together:
# named integer vector => stdout(console)
vec1[vec_nm_order]   vec2[vec_nm_order]
  • Related