如何使用 map* 和 mutate 将列表转换为一组附加列?

2024-01-16

我已经尝试过这段代码的数百种排列字面上的天尝试获得一个可以完成我想要的功能,但我最终放弃了。感觉这绝对是可行的,而且我已经很接近了!

我试图通过下面的代表回到这里的核心问题。

基本上我有一个单行数据框,其中一列包含字符串列表(“概念”)。我想为每个字符串创建一个附加列,使用mutate,理想情况下列从字符串中获取其名称,然后用函数调用的结果填充列(?现在哪个函数并不重要? - 我只需要函数的基础设施才能工作。 )

像往常一样,我觉得我一定错过了一些明显的东西......也许只是一个语法错误。 我也想知道是否需要使用purrr::map,也许更简单的矢量化映射会很好地工作。

我觉得新的专栏被命名了..1而不是概念名称,而是关于问题所在的一点线索。

我可以通过手动调用每个概念来创建我想要的数据框架(请参阅 reprex 的结尾),但由于不同数据框架的概念列表不同,我想使用管道和 tidyverse 技术来实现此功能,而不是手动执行。

我已阅读以下问题来寻求帮助:

  • 如何使用 purrr 中的映射和 dplyr::mutate 基于列对创建多个新列 https://stackoverflow.com/questions/49816669/how-to-use-map-from-purrr-with-dplyrmutate-to-create-multiple-new-columns-base
  • 如何使用 purrr:map 函数使用动态变量改变多列? https://stackoverflow.com/questions/57183024/how-to-mutate-multiple-columns-with-dynamic-variable-using-purrrmap-function
  • (R) 将 map() 与列表列一起使用的更简洁方法 https://stackoverflow.com/questions/53938745/r-cleaner-way-to-use-map-with-list-columns
  • 使用 purrr 和预定义函数添加多个输出变量 https://stackoverflow.com/questions/51978138/add-multiple-output-variables-using-purrr-and-a-predefined-function
  • 使用 purrr 创建新变量(如何做到这一点?) https://stackoverflow.com/questions/52607511/creating-new-variables-with-purrr-how-does-one-go-about-that
  • 如何使用动态名称计算 R 数据框中的多个新列 https://stackoverflow.com/questions/58641327/how-to-compute-multiple-new-columns-in-a-r-dataframe-with-dynamic-names

但这些都没有完全帮助我解决我遇到的问题。 [edit:在最后一个 q 中添加到该列表中,这可能是我需要的技术]。

<!-- language-all: lang-r -->


    # load packages -----------------------------------------------------------

    library(rlang)
    library(dplyr)
    library(tidyr)
    library(magrittr)
    library(purrr)
    library(nomisr)



    # set up initial list of tibbles ------------------------------------------

    df <- list(
      district_population = tibble(
        dataset_title = "Population estimates - local authority based by single year",
        dataset_id = "NM_2002_1"
      ),
      jsa_claimants = tibble(
        dataset_title = "Jobseeker\'s Allowance with rates and proportions",
        dataset_id = "NM_1_1"
      )
    )


    # just use the first tibble for now, for testing --------------------------
    # ideally I want to map across dfs through a list -------------------------

    df <- df[[1]]

    # nitty gritty functions --------------------------------------------------

    get_concept_list <- function(df) {
      dataset_id <- pluck(df, "dataset_id")
      nomis_overview(id = dataset_id,
                     select = c("dimensions", "codes")) %>%
        pluck("value", 1, "dimension") %>%
        filter(!concept == "geography") %>%
        pull("concept")
    }

    # get_concept_list() returns the strings I need:
    get_concept_list(df)
    #> [1] "time"     "gender"   "c_age"    "measures"

    # Here is a list of examples of types of map* that do various things,
    # none of which is what I need it to do
    # I'm using toupper() here for simplicity - ultimately I will use
    # get_concept_info() to populate the new columns

    # this creates four new tibbles
    get_concept_list(df) %>% 
      map(~ mutate(df, {{.x}} := toupper(.x)))
    #> [[1]]
    #> # A tibble: 1 x 3
    #>   dataset_title                                               dataset_id ..1  
    #>   <chr>                                                       <chr>      <chr>
    #> 1 Population estimates - local authority based by single year NM_2002_1  TIME 
    #> 
    #> [[2]]
    #> # A tibble: 1 x 3
    #>   dataset_title                                               dataset_id ..1   
    #>   <chr>                                                       <chr>      <chr> 
    #> 1 Population estimates - local authority based by single year NM_2002_1  GENDER
    #> 
    #> [[3]]
    #> # A tibble: 1 x 3
    #>   dataset_title                                               dataset_id ..1  
    #>   <chr>                                                       <chr>      <chr>
    #> 1 Population estimates - local authority based by single year NM_2002_1  C_AGE
    #> 
    #> [[4]]
    #> # A tibble: 1 x 3
    #>   dataset_title                                               dataset_id ..1    
    #>   <chr>                                                       <chr>      <chr>  
    #> 1 Population estimates - local authority based by single year NM_2002_1  MEASUR~

    # this throws an error
    get_concept_list(df) %>% 
      map_chr(~ mutate(df, {{.x}} := toupper(.x)))
    #> Error: Result 1 must be a single string, not a vector of class `tbl_df/tbl/data.frame` and of length 3

    # this creates three extra rows in the tibble
    get_concept_list(df) %>% 
      map_df(~ mutate(df, {{.x}} := toupper(.x)))
    #> # A tibble: 4 x 3
    #>   dataset_title                                               dataset_id ..1    
    #>   <chr>                                                       <chr>      <chr>  
    #> 1 Population estimates - local authority based by single year NM_2002_1  TIME   
    #> 2 Population estimates - local authority based by single year NM_2002_1  GENDER 
    #> 3 Population estimates - local authority based by single year NM_2002_1  C_AGE  
    #> 4 Population estimates - local authority based by single year NM_2002_1  MEASUR~

    # this does the same as map_df
    get_concept_list(df) %>% 
      map_dfr(~ mutate(df, {{.x}} := toupper(.x)))
    #> # A tibble: 4 x 3
    #>   dataset_title                                               dataset_id ..1    
    #>   <chr>                                                       <chr>      <chr>  
    #> 1 Population estimates - local authority based by single year NM_2002_1  TIME   
    #> 2 Population estimates - local authority based by single year NM_2002_1  GENDER 
    #> 3 Population estimates - local authority based by single year NM_2002_1  C_AGE  
    #> 4 Population estimates - local authority based by single year NM_2002_1  MEASUR~

    # this creates a single tibble 12 columns wide
    get_concept_list(df) %>% 
      map_dfc(~ mutate(df, {{.x}} := toupper(.x)))
    #> # A tibble: 1 x 12
    #>   dataset_title dataset_id ..1   dataset_title1 dataset_id1 ..11  dataset_title2
    #>   <chr>         <chr>      <chr> <chr>          <chr>       <chr> <chr>         
    #> 1 Population e~ NM_2002_1  TIME  Population es~ NM_2002_1   GEND~ Population es~
    #> # ... with 5 more variables: dataset_id2 <chr>, ..12 <chr>,
    #> #   dataset_title3 <chr>, dataset_id3 <chr>, ..13 <chr>

    # function to get info on each concept (except geography) -----------------
    # this is the function I want to use eventually to populate my new columns

    get_concept_info <- function(df, concept_name) {
      dataset_id <- pluck(df, "dataset_id")
      nomis_overview(id = dataset_id) %>%
        filter(name == "dimensions") %>%
        pluck("value", 1, "dimension") %>%
        filter(concept == concept_name) %>%
        pluck("codes.code", 1) %>%
        select(name, value) %>%
        nest(data = everything()) %>%
        as.list() %>%
        pluck("data")
    }


    # individual mutate works, for comparison ---------------------------------
    # I can create the kind of table I want manually using a line like the one below

    # df %>% map(~ mutate(., measures = get_concept_info(., concept_name = "measures")))
    df %>% mutate(., measures = get_concept_info(df, "measures"))
    #> # A tibble: 1 x 3
    #>   dataset_title                                        dataset_id measures      
    #>   <chr>                                                <chr>      <list>        
    #> 1 Population estimates - local authority based by sin~ NM_2002_1  <tibble [2 x ~

<sup>Created on 2020-02-10 by the [reprex package](https://reprex.tidyverse.org) (v0.3.0)</sup>

Using !! and :=允许您动态命名列。然后,我们可以减少列表输出map() with reduce(),其中 left_joins() 使用数据集标题和 id 列列表中的所有数据帧。

df_2 <- 
  map(get_concept_list(df),
      ~ mutate(df,
               !!.x := get_concept_info(df, .x))) %>% 
  reduce(left_join, by = c("dataset_title", "dataset_id"))

df_2

# A tibble: 1 x 6
  dataset_title                                               dataset_id           time         gender          c_age       measures
  <chr>                                                       <chr>      <list<df[,2]>> <list<df[,2]>> <list<df[,2]>> <list<df[,2]>>
1 Population estimates - local authority based by single year NM_2002_1        [28 x 2]        [3 x 2]      [121 x 2]        [2 x 2]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 map* 和 mutate 将列表转换为一组附加列? 的相关文章

  • 如何按用户定义(例如非字母顺序)对数据框进行排序[重复]

    这个问题在这里已经有答案了 给定一个数据框dna gt dna chrom start chr2 39482 chr1 203918 chr1 198282 chrX 7839028 chr17 3874 以下代码重新排序dna by ch
  • 如何纠正 data.frame 上的字符编码

    我有一个像这样的数据框 data names lt data frame DATA c 1 5 rownames data names lt c IV xc1N JOS xc9 LUC xcdA RAM xd3N TO xd1O data
  • 将列表中的每个元素转换为数据框中的一列

    假设我有以下列表 d library combinat d permn c a b c 这看起来如下 1 1 a b c 2 1 a c b 3 1 c a b 4 1 c b a 5 1 b c a 6 1 b a c 是否可以将此列表的
  • 如何在 R 中的 for 循环内将值存储在向量中

    我正在开始使用 R 但我对以下问题感到非常沮丧 我试图将 for 循环内完成的某些计算的值存储到我之前定义的向量中 问题是如何进行索引 因为for循环迭代代码的次数取决于用户的输入 所以变量i不一定要从1开始 它可以从80开始 for举个例
  • `as.matrix` 和 `as.data.frame` S3 方法与 S4 方法

    我注意到定义as matrix or as data frame作为 S4 类的 S3 方法 使例如lm formula objS4 and prcomp object 开箱即用 如果它们被定义为 S4 方法 则这不起作用 为什么将方法定义
  • 行对名称中具有特定模式的列求和

    我有一个像这样的数据表 DT lt ata table data table ref rep 3L 4L nb 12 15 i1 c 3 1e 05 0 044495 0 82244 0 322291 i2 c 0 000183 0 155
  • 在r中的某个阈值处破坏 cumsum() 函数

    例如我有以下代码 cumsum 1 100 我想打破它 如果一个元素 i 1 大于3000 我怎样才能做到这一点 因此 而不是这个结果 1 1 3 6 10 15 21 28 36 45 55 66 78 91 105 120 136 15
  • R,使用具有两种以上可能性的二项式分布

    我知道这可能是基本的 但我似乎有一个心理障碍 假设您想要计算在一个骰子上掷出 4 5 或 6 的概率 在 R 中 这很简单 sum 1 6 1 6 1 6 这给出了 1 2 这是正确答案 然而 我内心深处 可能应该保留的地方 认为我应该能够
  • R Shinydashboard 自定义 CSS 到 valueBox

    我一直在尝试将 valueBox 的颜色更改为自定义颜色 超出 validColors 中可用的颜色 但一直无法这样做 我知道有一种方法可以使用标签来包含自定义 CSS 但是我无法将它们放在正确的位置 ui lt dashboardPage
  • 在包加载之前如何知道 R 中特定函数属于哪个包?

    例如 我知道许多流行的功能 例如tbl df 我通常不记得它属于哪个包 即data table or dplyr 所以我必须始终记住并加载一个包 但我做不到 tbl df除非我加载了正确的包 在 R 控制台本身加载或安装包之前 有没有办法知
  • R:按组,测试一个变量的每个值是否存在于另一个变量中

    我有一个数据框架 结构如下 a lt c 1 1 1 2 2 2 3 3 3 3 4 4 b lt c 1 2 3 1 2 3 1 2 3 4 1 2 c lt c NA NA 2 NA 1 1 NA NA 1 1 NA NA df lt
  • 将维基百科中的表格加载到 R 中

    我正在尝试从以下 URL 将最高法院法官表加载到 R 中 https en wikipedia org wiki List of Justices of the Supreme Court of the United States http
  • R:单纯形错误:在下标赋值中不允许使用 NA

    对于以下具有目标函数和约束的最小化 boot simplex返回错误 Error in tab pr lt tab pr tab pr pc pv o tab pr NAs are not allowed in subscripted as
  • StatET调试工具

    我想我只是很密集 但我似乎无法弄清楚如何在 Eclipse 中的 R 中使用调试工具 StatET 插件 有人有关于这个主题的任何提示或教程吗 StatET 2 00 现在对高级 可视化调试提供实验性支持 需要 Eclipse 3 6 或
  • rvest 函数 html_nodes 返回 {xml_nodeset (0)}

    我正在尝试抓取以下网站的数据框 http stats nba com game 0041700404 playbyplay http stats nba com game 0041700404 playbyplay 我想创建一个表格 其中包
  • 无法编译包“maps”

    当我安装 maps 包时 安装中出现警告 ld warning ignoring file Library Developer CommandLineTools SDKs MacOSX10 14 sdk usr lib libSystem
  • 如何将参数从 Excel/VBA 传递到 Rstudio 中的脚本

    我正在尝试使用 Rstudio 从 VBA 打开 R 脚本 同时将参数传递给 R 脚本 然后我可以使用 commandArgs 访问该脚本 该问题与此处描述的问题非常相似 WScript Shell 用于运行路径中包含空格且来自 VBA 的
  • 条件和分组 mutate dplyr

    假设我有以下每个抽屉库存增加的数据 gt socks year drawer nbr sock total 1990 1 2 1991 1 2 1990 2 3 1991 2 4 1990 3 2 1991 3 1 我想要一个二进制变量来标
  • 如何使用plotmath更新ggplot图例标签

    我正在尝试更新ggplot要使用的图例标签plotmath但是 当我这样做时 它将之前组合的图例分成两部分 通过一个例子可能更容易理解 test data and the default plot gives the correct col
  • 斯皮尔曼相关性和联系

    我正在一小组配对排名上计算斯皮尔曼的 rho 斯皮尔曼因处理领带不当而闻名 例如 取2组8个排名 即使两组中有6个是平局 相关性仍然很高 gt cor test c 1 2 3 4 5 6 7 8 c 0 0 0 0 0 0 7 8 met

随机推荐

  • Delphi/Pascal 有静态代码分析工具吗? [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 Delphi Pascal 有静态代码分析工具吗 我见过很多 C 和 NET 的选项 但没有看到 De
  • java中如何将字符串转换为比特流

    如何将字符串转换为位 0 和 1 的流 我做了什么我采取了一个字符串 然后将其转换为一个字符数组 然后我使用了方法 称为 forDigit char int 但它没有给我作为 0 和 1 流的字符 你能帮忙吗 另外我怎样才能从位到字符进行相
  • 如何使用selenium获取td元素的文本?

    我有一个 html 表格 我需要用硒获取 td 元素的文本 html结构 table tbody tr td b Success b You have transferred 1 000 00 USD to DIST2 Your balan
  • 从 iPhone 发送 UDP 数据包

    有人有关于从 iPhone SDK 发送 UDP 数据包的好教程吗 EDIT 事实上 做到这一点真的很容易 RTFM 包含 AsyncUdpSocket 后 只需在标头中添加以下内容 AsyncUdpSocket socket 主要是 NS
  • Python Rich 表中的列表列表

    鉴于以下内容 我怎样才能将动物 年龄和性别放入每个表格单元格中 目前 所有数据最终都存储在一个单元格中 谢谢 from rich console import Console from rich table import Table lis
  • Appium Send keys() 函数发送中文字符作为英文字符串的一部分

    使用appium时send keys 函数在文本字段中发送名称 除了名称之外 文本字段中还会出现一些随机的汉字 我们在能力中使用 capabilities setCapability unicodeKeyboard true 甚至认为我们无
  • 基于行中的值的“开始”和“结束”日期

    我有一个可以找到的输入数据示例here https github com veronique ka tests blob master input xlsx input 我需要根据每行中的数据添加两列 开始日期 和 结束日期 开始日期 当所
  • 无法从 PATH 环境变量中删除 cygwin

    我最近不得不重新安装 Cygwin 在这样做时 我遇到了某些应用程序的问题 因为 Cygwin 似乎已附加到我的 PATH 环境变量中 我尝试按照这些说明删除它https www java com en download help path
  • 如何使用 SSMS 中的表值参数执行存储过程

    当我右键单击存储过程并选择执行存储过程命令时 我应该将什么作为值传递给表值参数 我不是在谈论 SSMS 查询 窗口 我说的是当您右键单击 SP 时显示的 执行过程 对话框 我可以通过此屏幕直接向 SP 提供参数值吗 这是可以做到的 例如 假
  • 如何在 Ruby 中将字符串转换为常量?

    如何转换字符串 User to User Object const get User 无需 ActiveSupport
  • PyGTK中动态修改/刷新菜单内容

    我正在尝试在我用 PyGTK 编写的 GUI 的菜单中实现最近打开的项目列表 我像这样初始化菜单 self filemenu gtk Menu self init file menu self fileitem gtk MenuItem F
  • 在多项活动中使用 Espresso 空闲资源

    我有一个启动第二个活动的第一个活动 在第二个活动中我有一个加载对话框 不是 AsyncTask 我需要让 Espresso 等到对话框消失后再继续测试 我必须在哪里实现 IdlingResource 我怎样才能让它等待dismissDial
  • 将向量作为 void 指针传递给函数

    我有一个回调函数 需要一个void 作为传递参数的参数 我想将向量传递给函数 该函数将被多次调用 因此在回调过程完成后 我希望能够迭代所有已调用的元素push back 通过回调 static void cb void data vecto
  • Angular 应用程序中 Font Awesome 字体出现 CORS 错误

    我已经运行 Angular 和 Material 一段时间了 但是这个问题突然出现并让我难住了 我正在运行来自 IntelliJ 的 Angular 应用程序 它开始出现在我的控制台中 访问位于 的字体https fonts gstatic
  • .NET 将外部 CSS 转换为内联 CSS [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 我正在寻找一个将外部 CSS 转换为内联 CSS 的工具 生成的 HTML 用于电子邮件和 PDF 创
  • 使用 SwiftUI 制作按钮闪烁动画

    如何在 SwiftUI 中制作边框颜色变化动画 这是 UIKit 的代码 extension UIButton func blink setColor UIColor repeatCount Float duration Double se
  • Android 单元测试没有被嘲笑

    我跟着本指南 https sites google com a android com tools tech docs unit testing support但我遇到了这个错误 junit framework AssertionFaile
  • 将鼠标监听器添加到 JTextPane 中插入的 JLabel/JButton

    我遇到一个问题 当我尝试将鼠标侦听器添加到 JTextPane 中的 JLabel 或 JButton 时 出现错误 无法通过调用转换转换为鼠标侦听器 我更愿意将该组件放在 JEditorPane 中 我还听说可以使用 HyperlinkE
  • 如果我故意标记一个函数[我知道可能会抛出] noexcept 以在发生异常时立即终止,我的代码是否格式不正确? [复制]

    这个问题在这里已经有答案了 我知道 标记一个函数noexcept 在某些情况下 可能有助于获得许多很棒的优化 例如移动语义 但是假设 我的代码中有一个函数执行非常关键的操作 如果该函数失败 则意味着发生了非常糟糕的事情以至于无法恢复 并且该
  • 如何使用 map* 和 mutate 将列表转换为一组附加列?

    我已经尝试过这段代码的数百种排列字面上的天尝试获得一个可以完成我想要的功能 但我最终放弃了 感觉这绝对是可行的 而且我已经很接近了 我试图通过下面的代表回到这里的核心问题 基本上我有一个单行数据框 其中一列包含字符串列表 概念 我想为每个字