【问题标题】:perform calculation across columns of type list跨列表类型的列执行计算
【发布时间】:2021-08-06 10:31:10
【问题描述】:

我有一个包含列表类型列的数据框:

       h1      h2      h3
1 6, 5.25 66, 4.2  4, 4.2
2   5, 11   7, 10   7, 10
3   6, 11  16, 11  16, 11
4 6, 0.25 7, 2.50 7, 7.77

我想将每列中的第一个值与第二个值相乘,所以在h1this 中将是6*5.255*116*11 等。

我在dplyr 中尝试过这段代码,但它给出了一个错误:

library(dplyr)
df0 %>%
  mutate(across(c(everything()), 
                ~ as.numeric(.x)[1]*12 + as.numeric(x.)[2]))  
Error: Problem with `mutate()` input `..1`.
x 'list' object cannot be coerced to type 'double'
ℹ Input `..1` is `(function (.cols = everything(), .fns = NULL, ..., .names = NULL) ...`.

可重现的数据:

structure(list(h1 = list(c("6", "5.25"), c("5", "11"), c("6", 
"11"), c("6", "0.25")), h2 = list(c("66", "4.2"), c("7", "10"
), c("16", "11"), c("7", "2.50")), h3 = list(c("4", "4.2"), c("7", 
"10"), c("16", "11"), c("7", "7.77"))), class = "data.frame", row.names = c(NA, 
-4L))

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    一种解决方案可能是:

    df %>%
        mutate(across(everything(), ~ map_dbl(., function(y) reduce(as.numeric(y), `*`))))
    
        h1    h2     h3
    1 31.5 277.2  16.80
    2 55.0  70.0  70.00
    3 66.0 176.0 176.00
    4  1.5  17.5  54.39
    

    将第一个元素与一个常数相乘:

    df %>%
        mutate(across(everything(), ~ map_dbl(., function(y) reduce(as.numeric(y) * c(12, 1), `*`))))
    

    【讨论】:

    • 漂亮!如果我想将第一个值与12 相乘并将第二个值添加到产品中,这将如何改变?
    • 知道了!非常感谢! df %>% mutate(across(everything(), ~ map_dbl(., function(x) as.numeric(x)[1] * 12 + as.numeric(x)[2])))
    • 更新了答案。
    【解决方案2】:

    你可以使用 -

    library(dplyr)
    library(purrr)
    
    df %>%
      mutate(across(.fns = function(x) map_dbl(x, ~prod(as.numeric(.)))))
    
    #    h1    h2     h3
    #1 31.5 277.2  16.80
    #2 55.0  70.0  70.00
    #3 66.0 176.0 176.00
    #4  1.5  17.5  54.39
    

    在基础 R 中,您可以组合 lapplysapply -

    df[] <- lapply(df, function(x) sapply(x, function(y) prod(as.numeric(y))))
    

    【讨论】:

      猜你喜欢
      • 2011-05-27
      • 1970-01-01
      • 2015-01-17
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      • 1970-01-01
      相关资源
      最近更新 更多