编写计算百分比的函数并将其放入数据框的新列中

Write Function to Calculate Percentage and Place it in a New Column of the Data Frame

我有一个数据框,其中一名运动员的表现评分为 "Good"、"Fair" 和 "Poor"。

我想编写一个函数来执行以下操作:

生成一个新的数据框,其中包含 运动员姓名 运动员获得"Good"评分

的次数百分比
Player <- c("Jordan", "Jordan", "Jordan", "Jordan", "Jordan", "Jordan", 
"Jordan","Jordan","Jordan", "Barkley", "Barkley", "Barkley", "Barkley", 
"Barkley", "Olajuwon", "Olajuwon", "Olajuwon", "Olajuwon", "Olajuwon", 
"Kemp", "Kemp", "Kemp", "Kemp", "Kemp", "Kemp")

Rating <- c("Good", "Fair", "Good", "Good", "Good", "Poor", "Good", "Good",  
"Good", "Fair", "Fair", "Poor", "Good", "Good", "Good", "Fair", "Good", 
"Fair", "Good", "Good", "Good", "Good", "Good", "Good", "Poor")

df <- data.frame(Player, Rating)

我想要的输出是:

Player    PercentGood
Jordan    77.8%
Barkley   40.0%
Olajuwon  60.0%
Kemp      83.3%

当我收到文件时,百分比不包括在内,所以每次向我发送更新的文件时我都想运行这个。

所以文件已发送,我应用代码并生成一个新的数据框,它为我提供了运动员获得 "Good"

评级的百分比摘要

谢谢。

这是使用 scales::percent 格式化百分比的 tidyverse 解决方案。

它首先创建一个新变量good或不编码为1或0。然后为每个玩家计算1s的百分比。

library(tidyverse)
library(scales)
df %>% mutate(good = ifelse(Rating == "Good", 1, 0)) %>% 
  group_by(Player = fct_inorder(Player)) %>% 
  summarise(PercentGood = percent(mean(good)))

# A tibble: 4 x 2
#  Player   PercentGood
#  <fct>    <chr>  
#1 Jordan   77.8%  
#2 Barkley  40.0%  
#3 Olajuwon 60.0%  
#4 Kemp     83.3%