gpt4 book ai didi

r - Purrr 将函数映射到除一列以外的所有列

转载 作者:行者123 更新时间:2023-12-05 05:38:59 26 4
gpt4 key购买 nike

我想对“ID”以外的所有列应用 Blom 转换。由于它们都是数字,map_ifis.numeric 在这里不起作用。

library(rcompanion)
data("mtcars")

# Get a list of the columns that I would like to apply the Blom transformation
col_names = colnames(mtcars)

# Create the column ID so each row has a unique identifier
mtcars = mtcars %>% mutate(id = row_number())

我想到的是:

mtcars = map_if(mtcars, names(.) %in% col_names ~ rcompanion::blom(.x, method = "blom")

但是我收到一个错误:!无法将双面公式 `.f` 转换为函数。

最佳答案

如果我们使用 across,这可以在 dplyr 内部完成

library(dplyr)
mtcars <- mtcars %>%
mutate(across(all_of(col_names), rcompanion::blom, method = "blom"))

-输出

> head(mtcars)
mpg cyl disp hp drat wt qsec vs am gear
Mazda RX4 0.2353289 -0.1168527 -0.23532887 -0.2754823 0.3989603 -0.62056827 -0.9368471 -0.5741128 0.8223940 0.3989603
Mazda RX4 Wag 0.2353289 -0.1168527 -0.23532887 -0.2754823 0.3989603 -0.35721583 -0.4846749 -0.5741128 0.8223940 0.3989603
Datsun 710 0.6684036 -0.9368471 -0.93684711 -0.8223940 0.2754823 -0.82239396 0.5288648 0.7690553 0.8223940 0.3989603
Hornet 4 Drive 0.3989603 -0.1168527 0.11685275 -0.2754823 -0.6684036 -0.03887224 0.8223940 0.7690553 -0.5288648 -0.7178201
Hornet Sportabout -0.1168527 0.7690553 0.99892823 0.3572158 -0.4846749 0.19555148 -0.4846749 -0.5741128 -0.5288648 -0.7178201
Valiant -0.1955515 -0.1168527 0.03887224 -0.5288648 -1.8134176 0.35721583 1.6411071 0.7690553 -0.5288648 -0.7178201
carb id
Mazda RX4 0.7690553 1
Mazda RX4 Wag 0.7690553 2
Datsun 710 -1.2138469 3
Hornet 4 Drive -1.2138469 4
Hornet Sportabout -0.3160850 5
Valiant -1.2138469 6

关于r - Purrr 将函数映射到除一列以外的所有列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72793782/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com