【问题标题】:Efficient method to add a column to a listcolumn in r将列添加到 r 中的列表列的有效方法
【发布时间】:2018-04-15 23:55:22
【问题描述】:

如何在列表列中创建新列?我只能通过变异成一个新的列表列来做到这一点。

此外,我发现下面的双重突变与其他方法相比相当慢。 mutate 会增加很多开销吗?

library(repurrrsive)
library(tidyverse) 
#> ── Attaching packages ─────────────────────────────────────────────────────────────────────────── tidyverse 1.2.1 ──
#> ✔ ggplot2 2.2.1     ✔ purrr   0.2.4
#> ✔ tibble  1.4.2     ✔ dplyr   0.7.4
#> ✔ tidyr   0.8.0     ✔ stringr 1.3.0
#> ✔ readr   1.1.1     ✔ forcats 0.3.0
#> ── Conflicts ────────────────────────────────────────────────────────────────────────────── tidyverse_conflicts() ──
#> ✖ dplyr::filter() masks stats::filter()
#> ✖ dplyr::lag()    masks stats::lag()

system.time(rep(
  gap_m<-gap_nested %>% 
  mutate(new_list=
           map(data,~ .x %>% mutate(pop_str=str_sub(pop,end = 4))))))
#>    user  system elapsed 
#>   0.087   0.005   0.091


system.time(gap_c<-gap_nested %>% 
              mutate(new_list=
                       map(data,~ cbind(.x,pop_str=str_sub(.x$pop,end=4),stringsAsFactors=F))))
#>    user  system elapsed 
#>   0.017   0.000   0.017

system.time(gap_b<-gap_nested %>% 
              mutate(new_list=
                       map(data,~ bind_cols(.x,pop_str=str_sub(.x$pop,end=4)))))
#>    user  system elapsed 
#>    0.02    0.00    0.02

【问题讨论】:

    标签: r tidyverse purrr tibble


    【解决方案1】:

    做你做的,但将结果保存回data

    mutate(.df, data = map(data, .f))
    

    【讨论】:

      猜你喜欢
      • 2019-03-05
      • 1970-01-01
      • 2021-09-10
      • 1970-01-01
      • 2013-01-28
      • 2011-07-13
      • 2021-08-12
      • 1970-01-01
      • 2021-10-04
      相关资源
      最近更新 更多