# [R] How do I multiply labeled vectors of numbers?

Gabor Grothendieck ggrothendieck at gmail.com
Thu Dec 11 03:51:35 CET 2008

```You probably want Marc's solution but just in case note that zoo's merge
supports zero fill which means that if you represented the two as zoo
objects whose "times" are cat, dog, ...  then we would have:

File1 <- "type    n
dog        2
cat        4
horse    6"

File2 <- "type    n
horse    1
dog        3
cat        9
mouse 11"

library(zoo)

z <- merge(z1, z2, fill = 0)
zz <- z[,1] * z[,2]

Also note that coredata(zz) and time(zz) extract the data and times
respectively.

On Wed, Dec 10, 2008 at 6:17 PM, Bill McNeill (UW)
<billmcn at u.washington.edu> wrote:
> I'm an R newbie trying to do an operation that seems like it should be very
> simple, but after much playing around with the interface and reading "An
> Introduction to R" I can figure out how to do it.
>
> I have two text files.  File1 contains:
>
> type    n
> dog        2
> cat        4
> horse    6
>
> File2 contains:
>
> type    n
> horse    1
> dog        3
> cat        9
> mouse 11
>
> I want to read both files into R and multiply corresponding values of n so
> that I end up with:
>
> dog       2*3 = 6
> cat        4*9 = 36
> horse    6*1 = 6
> mouse  0*11 = 0
>
> Note that the type rows are not necessarily in the same order in the two
> files, and that a missing type gets a default n = 0 value.
>
> I figure the way to do this is use read.table and do the appropriate
> manipulation of the factors, but I can't figure out what those manipulations
> would be.  Basically I want to use a factor table as a hash table, but I
> haven't been able to figure out how to do this, which makes me think I'm not
> conceptualizing this is the correct R-ish way.
>
> Thanks.
> --
> Bill McNeill
> http://staff.washington.edu/billmcn/index.shtml
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help