Home > Software engineering >  Multiple list functions convert to dplyr in R
Multiple list functions convert to dplyr in R

Time:02-03

I have the following code, in which I have three lists and I am sort of trying to calculate the MSE.

seg_mean <- list(c(3.5,2.5),c(6.5,5.5),c(9.2,8.8),c(5.3,4.7))
mean_tot <- list(c(3,3),c(6,6),c(9,9),c(5,5))
seg_len <- list(20,18,17,15)

MSE <- mapply('-', seg_mean, mean_tot, SIMPLIFY = FALSE) #element wise difference between seg_mean and mean_tot
MSE <- lapply(MSE, function(x) x^2) #element wise squaring
MSE <- mapply('/', MSE, seg_len, SIMPLIFY = FALSE) #dividing each list element by seg_len

This works. My question is can I make these lines of code easier by using %>% from dplyr package in R? I am not sure how it will work but I am hoping it would look like

MSE <- mapply('-', seg_mean, mean_tot, SIMPLIFY = FALSE) %>% lapply(function(x) x^2) %>% mapply('/', seg_len, SIMPLIFY = FALSE)

CodePudding user response:

With |> (base R's native pipe), you can do:

mapply('-', seg_mean, mean_tot, SIMPLIFY = FALSE) |>
  lapply(function(x) x^2) |>
  mapply(FUN = '/', seg_len, SIMPLIFY = FALSE)

It also works with %>%. The difference is in the second mapply, where one needs to specify the first argument, otherwise it'll get interpreted as mapply(., '/', seg_len, ...) instead of mapply('/', ., seg_len, ...)

  • Related