[R] How do I multiply labeled vectors of numbers?
Marc Schwartz
marc_schwartz at comcast.net
Thu Dec 11 00:39:24 CET 2008
on 12/10/2008 05:17 PM Bill McNeill (UW) 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.
F3 <- merge(F1, F2, by = "type", all = TRUE)
> F3
type n.x n.y
1 cat 4 9
2 dog 2 3
3 horse 6 1
4 mouse NA 11
# Convert NA's to 0
F3[is.na(F3)] <- 0
> F3
type n.x n.y
1 cat 4 9
2 dog 2 3
3 horse 6 1
4 mouse 0 11
F3$prod <- F3$n.x * F3$n.y
> F3
type n.x n.y prod
1 cat 4 9 36
2 dog 2 3 6
3 horse 6 1 6
4 mouse 0 11 0
See ?merge
HTH,
Marc Schwartz
More information about the R-help
mailing list