【发布时间】:2021-01-10 14:45:14
【问题描述】:
下午好,
我正在尝试从以下数据中过滤包含 94 种不同商品以及它们在不同时间售出多少商品的数据框,按总销量最高的 15 种商品:
structure(list(Time = c("07", "07", "07", "07", "07", "08"),
Item = c("Bread", "Coffee", "Medialuna", "Pastry", "Toast",
"Afternoon with the baker"), Transactions = c(2L, 13L, 6L,
2L, 1L, 3L)), row.names = c(NA, -6L), groups = structure(list(
Time = c("07", "08"), .rows = structure(list(1:5, 6L), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = 1:2, class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))
我已经按名称知道了 15 个最受欢迎的项目(“咖啡”、“茶”、“面包”等),并且我尝试使用以下代码对数据框进行子集化:
SalesPerTimePerItem <- subset(SalesPerTimePerItem,
Item == c("Coffee",
"Tea",
"Bread",
"Cake",
"Pastry",
"Sandwich",
"Medialuna",
"Hot chocolate",
"Cookies",
"Brownie",
"Farm House",
"Muffin",
"Alfajores",
"Juice",
"Soup"))
但是我收到了这个错误:
In Item == c("Coffee", "Tea", "Bread", "Cake", "Pastry", "Sandwich", :
longer object length is not a multiple of shorter object length
我还尝试了以下另一种方法:
SalesPTPI <- SalesPTPI[SalesPTPI$Item %in% c("Coffee",
"Tea",
"Bread",
"Cake",
"Pastry",
"Sandwich",
"Medialuna",
"Hot chocolate",
"Cookies",
"Brownie",
"Farm House",
"Muffin",
"Alfajores",
"Juice",
"Soup")]
但得到了错误:
Error: Must subset columns with a valid subscript vector.
i Logical subscripts must match the size of the indexed input.
x Input has size 3 but subscript `i` has size 631.
我的目标是利用这些数据创建一个条形图,如下所示:
但对象不同:
(x = Time, y = Transactions, fill = Item)
如何从顶部包含的数据框中仅过滤掉“咖啡”等响应?
【问题讨论】: