【问题标题】:second argument in map functionmap 函数中的第二个参数
【发布时间】:2018-07-09 09:25:48
【问题描述】:

我有一个这样的小标题:

uuu <- structure(list(Id = c("a", "b"),
                      lists = list(c(1:2), c(100:103))
),
.Names = c("Id", "lists"),
row.names = c(NA, 2L), class = c("tbl_df", "tbl", "data.frame"))

> uuu
# A tibble: 2 x 2
  Id    lists    
* <chr> <list>   
1 a     <int [2]>
2 b     <int [4]>

在此示例中,它有 2 行和 2 列,第一列是一个字符列,称为 id,第二列称为 lists,包含整数列表。

现在我想在列表元素上映射一个函数,例如sqrt 函数:

res <- uuu %>% mutate(res = map(lists, sqrt))

> res
# A tibble: 2 x 3
  Id    lists     res      
  <chr> <list>    <list>   
1 a     <int [2]> <dbl [2]>
2 b     <int [4]> <dbl [4]>

res 现在有一个新列,其中包含 sqrt 函数的所有结果。

现在我想取消列出 res 列中的结果,但我还想要一个新列来指示结果来自哪个 id

我可以像这样取消列出结果:

> unlist(res$res)
[1]  1.000000  1.414214 10.000000 10.049876 10.099505 10.148892

但我真正想要的是这样的(这里是手动完成的):

res2 <- data.frame(res = unlist(res$res),
            ids = c(rep("a", 2), rep("b", 4)))

> res2
        res ids
1  1.000000   a
2  1.414214   a
3 10.000000   b
4 10.049876   b
5 10.099505   b
6 10.148892   b

理想情况下,如果可能的话,我希望直接在映射部分中传递它,对于我定义自己的函数的情况,如下所示:

res <- uuu %>% mutate(res = map(lists, my_sqrt, id = id))

my_sqrt 是这样的:

my_sqrt <- function(x, id) return(sqrt(x), id)

【问题讨论】:

    标签: r dplyr purrr


    【解决方案1】:

    我们可以使用unnest

    library(tidyverse)
    res %>% 
      select(-lists) %>%
      unnest
    

    【讨论】:

      猜你喜欢
      • 2016-01-29
      • 1970-01-01
      • 2021-12-20
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      相关资源
      最近更新 更多