r - 如何在 R 中为大型数据框使用字典?

标签 r

我阅读了有关在 r 中创建字典的答案。

equivalent of a python dict in R

Is there a dictionary functionality in R

我有一个问题:如何在大型数据集中使用它? 数据结构是这样的:

enter image description here

子样本的输入是:

structure(list(...1 = c("category 1", NA, NA, NA, "total", "category 2", 
NA, NA, NA, "total"), Items = c("product 1", "product 2", "product 3", 
"product 4", NA, "product 1", "product 2", "product 3", "product 4", 
NA), price = c(1, 2, 3, 4, 10, 3, 4, 5, 6, 18)), row.names = c(NA, 
-10L), class = c("tbl_df", "tbl", "data.frame"))

我希望结果是这样的:

categoryx: {prodcut1:1, product2:2, product3:3....}

如果有 1000 个类别并且每个类别的产品数量不同,我该怎么办?上面两个链接中的答案,每个键的值应该手动添加,我不知道如何将它用于大型数据集。

或者有没有其他方法(除了创建字典)可以让我轻松提取每个类别的信息?

有人可以就这个问题给出想法吗?谢谢。

是否有可能在 python 中得到像字典(或字典列表)这样的结果?

例如 dict={category1: {prodcut1:1, product2:2, product3:3....}, category2: {prodcut1:3, product2:4, product3:5....} } } p>

所以我可以知道类别的索引并使用索引从字典中提取信息,也许它就像这样一个数据框:

            item      price

categoryx    product1   2
             product2   3

所以我可以针对特定类别进行操作?

最佳答案

hashmap 字典列表:

dat <-
  structure(
    list(
      ...1 = c("category 1", NA, NA, NA, "total", "category 2",
               NA, NA, NA, "total"),
      Items = c(
        "product 1",
        "product 2",
        "product 3",
        "product 4",
        NA,
        "product 1",
        "product 2",
        "product 3",
        "product 4",
        NA
      ),
      price = c(1, 2, 3, 4, 10, 3, 4, 5, 6, 18)
    ),
    row.names = c(NA,-10L),
    class = c("tbl_df", "tbl", "data.frame")
  )

library(hashmap)

dat_clean <- tidyr::fill(dat[!is.na(dat[["Items"]]), ], 1)

list_of_dicts <- lapply(split(dat_clean, dat_clean[[1]]), function(d){
  hashmap(d[["Items"]], d[["price"]])  
})

list_of_dicts
# $`category 1`
# ## (character) => (numeric)  
# ## [product 1] => [+1.000000]
# ## [product 3] => [+3.000000]
# ## [product 4] => [+4.000000]
# ## [product 2] => [+2.000000]
# 
# $`category 2`
# ## (character) => (numeric)  
# ## [product 1] => [+3.000000]
# ## [product 3] => [+5.000000]
# ## [product 4] => [+6.000000]
# ## [product 2] => [+4.000000]


# get totals:
lapply(list_of_dicts, function(dict){
  sum(dict$values())
})
# $`category 1`
# [1] 10
# 
# $`category 2`
# [1] 18

关于r - 如何在 R 中为大型数据框使用字典?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64111179/

相关文章:

r - 如何使用 ggvis 和映射包(即 ggmap)在 map 上交互地绘制空间数据

c# - 如何从 C# 代码运行 R 脚本?

r - 根据上一行有条件地重命名该值

r - 如何使用 R 函数 download.file?

r - 统计分析和报告撰写的工作流程

r - 将矩阵转换为 R 中的数据框

r - 根据列中的唯一值计算点数

r - 从日期中提取年份的天数

R 避免 x 轴自动缩放为 10 的幂

r - 是否可以从另一个包中的函数 @inheritParams ?