我刚开始学习使用R.如何在每个产品类别中找到每月价格涨幅最大的十大产品?
答案 0 :(得分:2)
如果你可以使用包dplyr:
library(dplyr)
df <- read.table(text="
Category, Product, PrevMonthPrice, CurrentMonthPrice
Food,Orange,5,10
Clothing,Shirt,25,35
Food,Apple,2,4
Clothing,Hat,25,15
Food,Soup,4.5,3
Clothing,Coat,150,200
Food,Meat,9,11
Clothing,Scarf,20,25
Food,Rice,8,12
Clothing,Shoes,150,125", sep=",", header=TRUE)
df %>%
mutate(increase=CurrentMonthPrice-PrevMonthPrice) %>%
group_by(Category) %>%
arrange(-increase) %>%
top_n(2)
Source: local data frame [4 x 5]
Groups: Category [2]
Category Product PrevMonthPrice CurrentMonthPrice increase
(fctr) (fctr) (dbl) (int) (dbl)
1 Clothing Coat 150 200 50
2 Clothing Shirt 25 35 10
3 Food Orange 5 10 5
4 Food Rice 8 12 4
答案 1 :(得分:0)
您可以使用&#34; pure&#34;获得相同的结果R:
df$increase=df$CurrentMonthPrice-df$PrevMonthPrice
top=2
res=lapply(split(df,df$Category), function(xd){
xd[with(xd,order(-increase)),][1:top,]
})
do.call(rbind,res)