根据年份和其他分类变量添加共享列中的r中的数据框架
我现在有销售数据,状况和产品
Year <- c(2010,2010,2010,2010,2010,2010,2011,2011,2011,2011,2011,2011,2012,2012,2012,2012,2012,2012)
Sale <- c("30","45","23","33","24","11","56","19","45","56","33","32","89","33","12",18,10,17)
Condition <- c("New","New","New","Used","Used","Used","New","New","New","Used","Used","Used","New","New","New","Used","Used","Used")
Product <- c("a","b","c","a","b","c","a","b","c","a","b","c","a","b","c","a","b","c")
df <- data.frame(Year,Condition, Product, Sale)
,现在我想根据每年的状况变量来计算每种产品的份额。我尝试了以下代码,但根据总数按年和“条件”计算得出
df$percentage <- df$Sale/sum(df$Sale)*100
I have sales data by year, condition and products
Year <- c(2010,2010,2010,2010,2010,2010,2011,2011,2011,2011,2011,2011,2012,2012,2012,2012,2012,2012)
Sale <- c("30","45","23","33","24","11","56","19","45","56","33","32","89","33","12",18,10,17)
Condition <- c("New","New","New","Used","Used","Used","New","New","New","Used","Used","Used","New","New","New","Used","Used","Used")
Product <- c("a","b","c","a","b","c","a","b","c","a","b","c","a","b","c","a","b","c")
df <- data.frame(Year,Condition, Product, Sale)
Now I want to calculate the share of each product by condition variable within each year. I tried the following code, but it calculates based on total no by year and "condition"
df$percentage <- df$Sale/sum(df$Sale)*100
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先使用
type.convert(as.is = true)
将从字符到数字,然后按所需列进行分组,然后应用
汇总
:请注意,在您提供的数据框中,由于您提供的数据,您将获得100个百分比:
此伪造的数据,
使用
您将获得:
更新:保留
sale> sale
column:用 替换突变
First convert
Sale
from character to numeric withtype.convert(as.is = TRUE)
,then group by the desired columns and apply
summarise
:Note that in your provided dataframe you will get 100 for percentage because of your provided data:
With this fake data
using this code
you will get:
Update: to keep
Sale
column: replacesummarise
withmutate
这是使用
ave()
的基本
解决方案。您可以用所需的任何其他内容替换AVE
中的分组变量。Here is a
base
solution usingave()
. You can replace grouping variables inave
with any others you want.