1

I have following data:

       item      Date     weights  
1    camera   2018-01-05  1.0000  
2    laptop   2018-01-05  1.0000  
3    laptop   2018-01-05  1.0000  
4  computer   2018-01-05  1.0000  
5    mobile   2017-12-25  0.9000  
6    mobile   2017-12-25  0.9000  
7    camera   2017-12-25  0.9000  
8    camera   2017-12-25  0.9000  
9    mobile   2017-12-15  0.8100  
10   mobile   2017-12-15  0.8100  
11   mobile   2017-12-15  0.8100  
12   mobile   2017-12-15  0.8100  
13   camera   2017-12-10  0.7290  
14   camera   2017-12-05  0.6561  

I want to fetch the frequency of item on the basis of weight:

For example:
for Camera frequency on the basis of weight should be:

(1+.9+.9+.729+.6561)/14
Gholamali Irani
  • 4,391
  • 6
  • 28
  • 59
Monty
  • 129
  • 2
  • 10

3 Answers3

2

Using data.table:

library(data.table)
# assuming your data object is called df, we turn it into a data.table
setDT(df)

df[, sum(weights) / nrow(df), by = item]
       item         V1
1:   camera 0.29893571
2:   laptop 0.14285714
3: computer 0.07142857
4:   mobile 0.36000000

In base R:

aggregate(weights ~ item, data = df, FUN = function(x) sum(x) / nrow(df))
      item    weights
1   camera 0.29893571
2 computer 0.07142857
3   laptop 0.14285714
4   mobile 0.36000000
s_baldur
  • 29,441
  • 4
  • 36
  • 69
2

With dplyr:

library(dplyr)

df %>% 
  group_by(item) %>% 
  summarise(freq = sum(weights) / nrow(.))

# A tibble: 4 x 2
  item       freq
  <chr>     <dbl>
1 camera   0.299 
2 computer 0.0714
3 laptop   0.143 
4 mobile   0.360 

To remove missing values when summarizing you can modify the third line in the chain to:

summarise(freq = sum(weights, na.rm = TRUE) / nrow(.))
tyluRp
  • 4,678
  • 2
  • 17
  • 36
0

With dplyr this works:

item <- c('camera', 'camera', 'laptop', 'camera', 'laptop', 'camera')
weights <- c(1, 0.5, 1, 0.9, 0.8, 0.7)
df <- data.frame(item, weights)
library(dplyr)
df %>% group_by(item) %>% summarise(mean = sum(weights)/nrow(df))

Result:

A tibble: 2 x 2
    item      mean
  <fctr>     <dbl>
1 camera 0.5166667
2 laptop 0.3000000
Ankur Sinha
  • 6,473
  • 7
  • 42
  • 73