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

Time:12-31

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

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

CodePudding user response:

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
  • Related