简体   繁体   中英

Weighted Mean in R

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??

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))

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM