【问题标题】:R multiply nested list with constant in the same rowR将嵌套列表与同一行中的常量相乘
【发布时间】:2021-04-07 23:05:26
【问题描述】:

我想将一个列表相乘,该列表存储在一个整洁的数据框中的嵌套列中:

数据看起来相当简单:

# A tibble: 3 x 4
  base    lin    sq sequence  
  <chr> <dbl> <dbl> <list>    
1 a     -0.49  1.14 <dbl [21]>
2 b     -0.04  0    <dbl [21]>
3 c     -0.02 -0.02 <dbl [21]>

现在我只想将sequence 列中列表的每个元素与同一行中的lin 值相乘。

我尝试了以下方法:

df %>%
  mutate(result = map(sequence, .f = function(x) {x * lin}))

但这会将每个序列与lin 的所有值相乘,而不仅仅是与每一行的常数相乘。

有什么想法吗? 非常感谢您的帮助!

数据在这里:

structure(list(base = c("a", "b", "c"), lin = c(-0.49, -0.04, 
-0.02), sq = structure(c(1.14, 0, -0.02), .Names = c("", "", 
"")), sequence = list(c(-0.794121067, -0.6289533995, -0.463785732, 
-0.2986180645, -0.133450397, 0.0317172704999999, 0.196884938, 
0.3620526055, 0.527220273, 0.6923879405, 0.857555608, 1.0227232755, 
1.187890943, 1.3530586105, 1.518226278, 1.6833939455, 1.848561613, 
2.0137292805, 2.178896948, 2.3440646155, 2.509232283), c(0.08829631, 
13.3151980495, 26.542099789, 39.7690015285, 52.995903268, 66.2228050075, 
79.449706747, 92.6766084865, 105.903510226, 119.1304119655, 132.357313705, 
145.5842154445, 158.811117184, 172.0380189235, 185.264920663, 
198.4918224025, 211.718724142, 224.9456258815, 238.172527621, 
251.3994293605, 264.6263311), c(0.732290268, 34.8192780496, 68.9062658312, 
102.9932536128, 137.0802413944, 171.167229176, 205.2542169576, 
239.3412047392, 273.4281925208, 307.5151803024, 341.602168084, 
375.6891558656, 409.7761436472, 443.8631314288, 477.9501192104, 
512.037106992, 546.1240947736, 580.2110825552, 614.2980703368, 
648.3850581184, 682.4720459))), row.names = c(NA, -3L), class = c("tbl_df", 
"tbl", "data.frame"))

【问题讨论】:

    标签: r list dplyr purrr


    【解决方案1】:

    我们需要map2,因为list 'sequence' 的每个元素都应该乘以相应的'lin' 值。如果我们使用function(x) {x * lin},它会将每个元素乘以 lin 的完整列值(在length 中也会有所不同)

    library(dplyr)
    library(purrr)
    df1 <- df %>%
       mutate(result = map2(sequence, lin, `*`))
    

    如果多于两列,则使用pmap

    df %>% 
      mutate(result = pmap(select(., -base), ~ (..1 * ..3) + (..2 * ..3 * ..3)))
    

    -输出

    # A tibble: 3 x 5
    #  base    lin    sq sequence   result    
    #  <chr> <dbl> <dbl> <list>     <list>    
    #1 a     -0.49  1.14 <dbl [21]> <dbl [21]>
    #2 b     -0.04  0    <dbl [21]> <dbl [21]>
    #3 c     -0.02 -0.02 <dbl [21]> <dbl [21]>
    

    或者rowwise

    df %>% 
      rowwise %>%
      mutate(result = list((lin * sequence) + 
             (sq * sequence * sequence))) %>%
      ungroup
    

    或者使用base R

    df$result <- Map(`*`, df$sequence, df$lin)
    

    【讨论】:

    • 一个令人难以置信的快速回复!太棒了,非常感谢!!如果我也想乘以 sq 列,我该怎么做?您可能已经猜到了,linsq 是线性的和平方的。所以我想为每个元素做:lin * element + sq * element * element。这是否也适用于map2
    • 很棒的东西 akrun,非常感谢!!解决了我所有的问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-03
    相关资源
    最近更新 更多