dplyr按组计算分数

格雷格

只有2个农场,但吨fruit试图查看哪个服务器场在3年内的性能更好,其中性能只是服务器场i /(服务器场1 +服务器场2,因此,fruit==peach服务器场1的性能为20%,而服务器场2的为80%

样本数据:

df <- data.frame(fruit = c("apple", "apple", "peach", "peach", "pear", "pear", "lime", "lime"),
                    farm = as.factor(c(1,2,1,2,1,2,1,2)), 'y2019' = c(0,0,3,12,0,7,4,6), 
                    'y2018' = c(5,3,0,0,8,2,0,0),'y2017' = c(4,5,7,15,0,0,0,0) )
> df
  fruit farm y2019 y2018 y2017
1 apple    1     0     5     4
2 apple    2     0     3     5
3 peach    1     3     0     7
4 peach    2    12     0    15
5  pear    1     0     8     0
6  pear    2     7     2     0
7  lime    1     4     0     0
8  lime    2     6     0     0
>

所需的输出:

 out
  fruit farm y2019 y2018    y2017
1 apple    1   0.0 0.625 0.444444
2 apple    2   0.0 0.375 0.555556
3 peach    1   0.2 0.000 0.318818
4 peach    2   0.8 0.000 0.681818
5  pear    1   0.0 0.800 0.000000
6  pear    2   1.0 0.200 0.000000
7  lime    1   0.4 0.000 0.000000
8  lime    2   0.6 0.000 0.000000
>

这是我能走的很远的地方:

df %>% 
  group_by(fruit) %>% 
  summarise(across(where(is.numeric), sum))
阿克伦

我们可以按“水果”分组,mutate across以“ y”开头的列将元素除以sum这些列中的值,if all值是0,然后返回0

library(dplyr)
df %>%
   group_by(fruit) %>% 
   mutate(across(starts_with('y'), ~ if(all(. == 0)) 0 else ./sum(.)))

# A tibble: 8 x 5
# Groups:   fruit [4]
#  fruit farm  y2019 y2018 y2017
#  <chr> <fct> <dbl> <dbl> <dbl>
#1 apple 1       0   0.625 0.444
#2 apple 2       0   0.375 0.556
#3 peach 1       0.2 0     0.318
#4 peach 2       0.8 0     0.682
#5 pear  1       0   0.8   0    
#6 pear  2       1   0.2   0    
#7 lime  1       0.4 0     0    
#8 lime  2       0.6 0     0    

注意:在这里,我们只使用了dplyr软件包,并且只需一步即可完成

或者另一种选择是adorn_percentagesjanitor

library(janitor)
library(purrr)
df %>%
    group_split(fruit) %>%
    map_dfr(adorn_percentages, denominator = "col") %>%
    as_tibble

或使用 data.table

library(data.table)
setDT(df)[, (3:5) := lapply(.SD, function(x) if(all(x == 0)) 0 
        else x/sum(x, na.rm = TRUE)), .SDcols = 3:5, by = fruit][]

或使用 base R

grpSums <- rowsum(df[3:5], df$fruit)
df[3:5] <- df[3:5]/grpSums[match(df$fruit, row.names(grpSums)),]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章