[R] Sum two Vectors of different length

Jessica Streicher j.streicher at micromata.de
Fri Aug 3 15:55:59 CEST 2012


Is the Index of what you cut off or add unimportant or do you have indices on which to compare them?

If you just want to have the same length, not depending on any indices:
 
v1<-1:9
v2<-1:10
minlength<-min(length(v1),length(v2))
v1[1:minlength]+v2[1:minlength]

If indices are important:

names(v1)<-1:9
names(v2)<-1:10
df1<-data.frame(v1,n=names(v1))
df2<-data.frame(v2,n=names(v2))

merge(df1,df2,by.x="n",by.y="n")
rowSums(merged[,-1])



On 03.08.2012, at 15:13, Alaios wrote:

> Dear all,
> in one part of my code I want to sum two vectors element-wise
> the problem is that either the 1st vector or the 2nd vector always have one or two less elements
> 
> example of my problem
> 
> In TotalVector + (datalist2[[1]]$dataset$Results[[j]]$Results[[time]]$Sweep) :
>   Länge des längeren Objektes
>          ist kein Vielfaches der Länge des kürzeren Objektes
> Browse[1]> str(TotalVector)
>  int [1:10308] 3032 3048 3075 2978 3026 3012 2933 2987 3063 3038 ...
> Browse[1]> str(datalist2[[1]]$dataset$Results[[j]]$Results[[time]]$Sweep)
>  int [1:10307] 2 1 3 1 5 6 3 1 0 2 ...
> 
> 
> as you can see the two vectors differ only in one element. As the sample is quite large it would be the same if I ignore the one extra element.
> There are times though that the missing elements can be 2 or 3 (but always the number is small enough so to be ignored)
> 
> 
> The major concern is that this "difference" can be either on the fist vector or either on the second vector. If I try to solve that with simple if statements the code gets too much of spaghetti... Is there a simple way when there is this length difference 
> 
> 
> either to 
> 
> 
> a. Ignore the extra elements
> -or-
> 
> b. Add the elements missing to the vector with the smaller length( one can just duplicate some of the existing values to reach the needed length)
> 
> How I can do either a or b?
> 
> I would like to thank you in advance for your help
> 
> Regards
> Alex
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list