【问题标题】:How to make purrr recognize colnames of df in a list?如何让 purrr 识别列表中 df 的 colnames?
【发布时间】:2021-05-27 12:08:09
【问题描述】:

我正在尝试将每个数据框中的名字和姓氏统一到数据框列表中。问题是 purrr 似乎无法识别 within 每个 df 的 colnames。

data$authors_list 中的每个 df 看起来都像

authid surname given-name
12345 Smith John
85858 Scott Jane

我想将“姓”和“名”合并到一个名为 AuN 的列中。

data <- data %>%
  mutate(authors_list = map(authors_list,
                            unite(col=AuN,
                            c(`given-name`,
                              surname),
                            sep = " ")))

但是,我收到以下错误。

Error in unite(col = AuN, c(`given-name`, surname), sep = " ") : 
  object 'given-name' not found

我刚开始使用 purrr,但我无法在网上找到类似问题的解决方案。任何帮助将不胜感激!

【问题讨论】:

  • 您有 data.frames 存储在 data.frame 列中吗?请使用dput() 之类的内容提供可重现的示例,以便我们可以将示例数据复制/粘贴到 R 中进行测试。您似乎没有将函数传递给map,您似乎正在调用一个可能是问题的函数。

标签: r dplyr purrr


【解决方案1】:

我想这就是你所追求的。您需要在统一调用中输入.x 以代替列表中的每个数据框。对于每一个,它将与您指定的参数结合。

library(tidyverse)

#Set up the data (but please in the future give us data so we don't have to set it up)
df <- tibble(authid = c(12345, 85858), surname = c("Smith", "Scott"), `given-name` = c("John","Jane"))
list_df <- list(df, df, df)

list_df_unite <- map(list_df, ~ unite(.x, AuN, c(`given-name`,surname), sep = " "))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2015-03-07
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多