作为业余爱好学习R,并使用一些炉石比赛
背景:使用dplyr到达此处:
todayhs %.%
group_by(hero, result) %.%
select(hero, opponent, result) %.%
summarise(
count = n())
数据:
hero result count
Mage loss 12
Mage win 9
Rogue loss 3
Rogue win 1
Warrior loss 6
Warrior win 5
预期结果:该特定英雄的百分比列
hero result count percent
Mage loss 12 57%
Mage win 9 43%
Rogue loss 3 75%
Rogue win 1 25%
Warrior loss 6 55%
Warrior win 5 45%
我的障碍:
我了解filter(hero =“Mage”)并使用prop.table将使我得到该单个类的百分比的结果,但是有没有办法一次性获取上述所有数据?
我的尝试
transform(todayhs.mage, percents = ifelse(hero == "Mage",
prop.table(todayhs.mage$count[1:2]),""))
给我
hero result count percents
Mage loss 12 0.571428571428571
Mage win 9 0.428571428571429
Rogue loss 3
Rogue win 1
Warrior loss 6
Warrior win 5
我认为我可以编写一个函数并将它们单独剥离..但这感觉不对。
也许有一种使用dplyr添加group_by(hero,count)的更好的方法吗?我在这挠头。
最佳答案
您可以尝试:
todayhs <- read.table(text="hero result count
Mage loss 12
Mage win 9
Rogue loss 3
Rogue win 1
Warrior loss 6
Warrior win 5",sep="",header=T,stringsAsFactors=F)
library(dplyr)
todayhs%>%
group_by(hero)%>%
mutate(percent=paste0(round(100*count/sum(count)),"%"))
# Source: local data frame [6 x 4]
#Groups: hero
# hero result count percent
# 1 Mage loss 12 57%
# 2 Mage win 9 43%
# 3 Rogue loss 3 75%
# 4 Rogue win 1 25%
# 5 Warrior loss 6 55%
# 6 Warrior win 5 45%