Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert tibble output of across() with lambda function to a vector form output of mutate?

I know that the across() returns a tibble with one column for each column in .cols and each function in .fns. Also scale() returns a matrix.

I tried some things but am unable to convert objects ‘jj’ or ‘kk’ to be the same as ‘ii’.

I know this might be a simple thing and I did try to search for relevant questions. Please point me towards a duplicate. Thank You

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

library(tibble)
library(dplyr)
# 
aa <- as_tibble(mtcars) %>% select(wt) 
#
ii <- aa %>% mutate(z = as.vector(scale(wt)))
jj <- aa %>% mutate(z = across(wt, scale))
kk <- aa %>% mutate(z = across(wt, ~ as.vector(scale(.))))
#
# #How to modify jj & kk above, so that these will be identical to ii
all(identical(ii, jj), identical(ii, kk))
#
str(ii)
#tibble [32 x 2] (S3: tbl_df/tbl/data.frame)
# $ wt: num [1:32] 2.62 2.88 2.32 3.21 3.44 ...
# $ z : num [1:32] -0.6104 -0.3498 -0.917 -0.0023 0.2277 ...
str(jj)
#tibble [32 x 2] (S3: tbl_df/tbl/data.frame)
# $ wt: num [1:32] 2.62 2.88 2.32 3.21 3.44 ...
# $ z : tibble [32 x 1] (S3: tbl_df/tbl/data.frame)
#  ..$ wt: num [1:32, 1] -0.6104 -0.3498 -0.917 -0.0023 0.2277 ...
#  .. ..- attr(*, "scaled:center")= num 3.22
#  .. ..- attr(*, "scaled:scale")= num 0.978
str(kk)
#tibble [32 x 2] (S3: tbl_df/tbl/data.frame)
# $ wt: num [1:32] 2.62 2.88 2.32 3.21 3.44 ...
# $ z : tibble [32 x 1] (S3: tbl_df/tbl/data.frame)
#  ..$ wt: num [1:32] -0.6104 -0.3498 -0.917 -0.0023 0.2277 ...

>Solution :

A solution to this problem would be

jj <- aa %>% mutate(across(wt, list(z = ~ as.vector(scale(.))), .names = "{.fn}"))

Test

> library(dplyr)
> aa <- tibble::as_tibble(mtcars) %>% select(wt) 
> ii <- aa %>% mutate(z = as.vector(scale(wt)))
> jj <- aa %>% mutate(across(wt, list(z = ~ as.vector(scale(.))), .names = "{.fn}"))
> identical(ii, jj)
[1] TRUE
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading