Chris Ruehlemann
Chris Ruehlemann

Reputation: 21440

perform calculation across columns of type list

I have a dataframe with columns of type list:

       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

I want to multiply the first value in each column with the second value, so in h1this would be 6*5.25, 5*11, 6*11, etc.

I've tried this code in dplyr but it gives an error:

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) ...`.

Reproducible data:

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

Upvotes: 2

Views: 101

Answers (2)

tmfmnk
tmfmnk

Reputation: 40171

One solution might be:

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

To multiple the first element with a constant:

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

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

You can use -

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

In base R, you can combine lapply and sapply -

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

Upvotes: 1

Related Questions