R将嵌套列表与同一行中的常量相乘

R multiply nested list with constant in the same row

我想乘以存储在整洁数据框中的嵌套列中的列表:

数据看起来相当简单:

# 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"))

我们需要 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)