【问题标题】:Why does using pipes and map fail on a list of data frames?为什么在数据框列表上使用管道和地图会失败?
【发布时间】:2019-06-01 11:38:50
【问题描述】:

我也有嵌套在一个带有标识符列的列表中。我想在每个嵌套的 tibble 上运行匿名函数。但是,当我使用管道引用我的主 df,然后引用包含我的数据映射的列表时不起作用。

# Creating the df
df_nested <- iris %>% group_by(Species) %>% nest()

# Does not work
# df_nested %>% 
# map(data, nrow)

# Works
map(df_nested$data, nrow)

我想了解为什么代码不能使用管道。

【问题讨论】:

    标签: r purrr rowwise


    【解决方案1】:

    这是因为当使用管道 (%&gt;%) 时,默认情况下第一个参数是从 LHS 传递的。

    当你在做的时候

    df_nested %>% map(data, nrow)
    

    你得到

    #$Species
    #[1] ".x[[i]]" "nrow"   
    
    #$data
    #[1] ".x[[i]]" "nrow"   
    
    #Warning messages:
    #1: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
    #2: In .f(.x[[i]], ...) : data set ‘nrow’ not found
    #3: In .f(.x[[i]], ...) : data set ‘.x[[i]]’ not found
    #4: In .f(.x[[i]], ...) : data set ‘nrow’ not found
    

    相同
    map(df_nested, data, nrow)
    

    如果你想使用你可能需要的管道

    df_nested$data %>% map(nrow)
    
    #[[1]]
    #[1] 50
    
    #[[2]]
    #[1] 50
    
    #[[3]]
    #[1] 50
    

    【讨论】:

      【解决方案2】:

      在使用nested 数据时使用mutate 总是更好:

      df_nested %>% 
         mutate(Nrow=map(data,nrow)) %>% 
         unnest(Nrow)
      # A tibble: 3 x 3
        Species    data               Nrow
        <fct>      <list>            <int>
      1 setosa     <tibble [50 x 4]>    50
      2 versicolor <tibble [50 x 4]>    50
      3 virginica  <tibble [50 x 4]>    50
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-01
        • 1970-01-01
        相关资源
        最近更新 更多