I want to see the best-performing products sales in a table and not in a plot.
Ex. Products = 1 2 3 4 5 6 7 8 9 10
Sales = 50 40 90 100 120 110 110 120 150 150
If there are over 1000's of datasets and I want to pick the top 5 sales based on products. what would be the code?
Tried using if-else function but doesn't seem to be working.
Q.2 can you share some references to understand the ifelse R functions concept ?
thanks in advance
FJCC
August 5, 2020, 8:10pm
2
The easiest way to get the top values may be to sort the data by Sales and take the first N rows.
DF <- data.frame(Prod = 1:10,
Sales = c(50, 40, 90, 100, 120, 110, 110, 120, 150, 150))
DF
#> Prod Sales
#> 1 1 50
#> 2 2 40
#> 3 3 90
#> 4 4 100
#> 5 5 120
#> 6 6 110
#> 7 7 110
#> 8 8 120
#> 9 9 150
#> 10 10 150
library(dplyr, warn.conflicts = FALSE)
DF <- arrange(DF, desc(Sales)) #Sort by Sales in descending order
# get a subset of the top 3 Sales
Top3Prod <- DF[1:3,]
Top3Prod
#> Prod Sales
#> 1 9 150
#> 2 10 150
#> 3 5 120
Created on 2020-08-05 by the reprex package (v0.2.1)
suppressPackageStartupMessages(library(dplyr))
charlatan::ch_color_name(n = 15) -> products
charlatan::ch_integer(n = 15) -> sales
as.data.frame(cbind(products,sales)) -> dataset
dataset %>% arrange(desc(as.numeric(sales))) %>% head(.,5)
#> products sales
#> 1 LightSalmon 927
#> 2 LavenderBlush 708
#> 3 LightBlue 706
#> 4 CadetBlue 676
#> 5 Blue 634
dataset %>% mutate(oddeven = ifelse(as.numeric(sales) %% 2 == 0,"even","odd"))
#> products sales oddeven
#> 1 CadetBlue 676 even
#> 2 LightSalmon 927 odd
#> 3 LightBlue 706 even
#> 4 MediumVioletRed 92 even
#> 5 OldLace 237 odd
#> 6 Blue 634 even
#> 7 Lime 425 odd
#> 8 LavenderBlush 708 even
#> 9 Aquamarine 198 even
#> 10 Linen 442 even
#> 11 LightSkyBlue 629 odd
#> 12 Beige 48 even
#> 13 Sienna 367 odd
#> 14 PaleVioletRed 371 odd
#> 15 Orange 170 even
Created on 2020-08-05 by the reprex package (v0.3.0)
ifelse
takes an expression, such as a == 5
that returns a logical value and returns one value if TRUE, and another if FALSE.
system
Closed
August 26, 2020, 8:22pm
4
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.