Home > OS >  Weighted Mean in R
Weighted Mean in R

Time:08-25

I have a time-series data with different lengths - a,b,c,d,e

 #printing a
 Time Series:
  Start = 1
  End = 42
  Frequency = 1
  [1] 60 
 
#printing b
Time Series:
  Start = 1
  End = 42
  Frequency = 1
  [1] 50 70  
 
#printing c
Time Series:
  Start = 1
  End = 42
  Frequency = 1
  [1] 40 70 100

 #and so on 

I am trying to get the mean of elements in all lists: #since there are 5 values available for 1st element

mean1 <- a[1] b[1] c[1] d[1] e[1] / 5 

 #since there are 4 values available for 2nd element

mean2<-  b[2] c[2] d[2] e[2] / 4

#next divide by 3 and 2...1

mean3<- c[3] d[3] e[3] / 3 and so on...

I need the mean of these values so that I can make a weighted mean for each element for further processing. Can anyone give suggestion on what to do to obtain the weighted mean from this data??

CodePudding user response:

We get the objects in a list, then get the mean from the list and do the weighted calculation

lst1 <- lapply(mget(letters[1:5]), unlist)
mx <- max(lengths(lst1))
lst2 <- lapply(lst1, `length<-`, mx)
(1/mx) * (rowSums(mapply(`*`, lst2,  
     rowMeans(simplify2array(lst2), na.rm = TRUE)), na.rm = TRUE))

CodePudding user response:

you could do:

l <- c(a,b,c,d,e)

tapply(unlist(l), sequence(lengths(l)), mean)
        1         2         3         4         5 
 6923.783 -2462.537 16402.663    62.005   432.800 
  • Related