Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two vectors of different length in R

Tags:

merge

r

vector

I've been struggling with this problem, and decided to ask for some help after some fails..

Here is my problem, I want to divide these two vectors based on the day, for instance 2012-12-11 will be 3/17 and 2012-12-12 should be 0/7. However I can't seem to figure out how to do this..

> ili

2012-12-11 2012-12-13 2012-12-14 2012-12-17 
     3          6          7          1 
> no.ili

2012-12-11 2012-12-12 2012-12-13 2012-12-14 2012-12-15 2012-12-16 2012-12-17 
    17          7        232        322         38         21         36 

The last attempt was to loop over the two vectors and add the value or zero to a new vector however when I use %in% it doesn't put the values in order (obviously) but if I use == it also doesn't work..

 days.ili <- unique(one.three$timestamp)
 days <- unique(one.week$timestamp)
 ili.vec <- rep(0, length(days))

 for (i in 1:length(days)) {
     if (days.ili[i] %in% days) {
         ili.vec[i] <- ili[i]
     } else {
         ili.vec[i] <- 0
     }
 }

I must be forgetting some thing since I'm not being able to see through this problem.. Can anyone give me any idea about the best way to achieve this in R?

Perhaps an option will be using merge ..

like image 844
psoares Avatar asked Jan 02 '13 11:01

psoares


People also ask

How do you compare vectors of different lengths?

Take a number of random vectors and multiply scalar first vector by each of them and second vector by each of them. As a result, we get two arrays of numbers of the same length, which can be interpreted as the coordinates of two vectors of the same length, which is not a problem to compare.

How do you compare two vectors?

A vector quantity has two characteristics, a magnitude and a direction. When comparing two vector quantities of the same type, you have to compare both the magnitude and the direction. On this slide we show three examples in which two vectors are being compared. Vectors are usually denoted on figures by an arrow.

Can you add vectors of different lengths in R?

You can add vectors of the same length or different lengths. You can add vectors of integer and decimal data types, but you can't add vectors of two completely different data types like string and integer.


1 Answers

Something like this:

res <- rep(0, length(no.ili))
where <- match( names(ili), names(no.ili) )
res[ where ] <- ili / no.ili[where]
names(res) <- names(no.ili)
res
# 2012-12-11 2012-12-12 2012-12-13 2012-12-14 2012-12-15 2012-12-16 2012-12-17 
# 0.17647059 0.00000000 0.02586207 0.02173913 0.00000000 0.00000000 0.02777778
like image 113
Romain Francois Avatar answered Oct 23 '22 07:10

Romain Francois