根据重量获取项目的频率

时间:2018-01-18 11:24:11

标签: r

我有以下数据:

       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  

我想根据weight

获取项目的频率

例如:
基于Camera的{​​{1}}频率应为:

weight

3 个答案:

答案 0 :(得分:2)

使用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

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

答案 1 :(得分:2)

使用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 

要在汇总时删除缺失值,您可以将链中的第三行修改为:

summarise(freq = sum(weights, na.rm = TRUE) / nrow(.))

答案 2 :(得分:0)

使用dplyr可以正常工作:

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

结果:

A tibble: 2 x 2
    item      mean
  <fctr>     <dbl>
1 camera 0.5166667
2 laptop 0.3000000