使用 purrr::map_df 仅在整数列上应用函数

问题描述 投票:0回答:2

这是我的代码。我需要使用 purrr::map_df 函数在数据框中的整数列上应用一个简单的函数,但我需要维护 character

fun1 <- function(x){(x - mean(x))/sd(x)}

df <- mtcars %>% rownames_to_column()

df %>% map_df(~  fun1(.x))
r purrr
2个回答
1
投票

你的预期输出到底是多少?像这样吗?

library(tidyverse)

fun1 <- function(x) {
  (x - mean(x)) / sd(x)
}

df <- mtcars  %>%
  rownames_to_column() %>%
  as_tibble()

df %>%
  mutate(across(where(is.numeric), fun1))


# A tibble: 32 × 12
   rowname              mpg    cyl    disp     hp   drat       wt   qsec     vs     am   gear   carb
   <chr>              <dbl>  <dbl>   <dbl>  <dbl>  <dbl>    <dbl>  <dbl>  <dbl>  <dbl>  <dbl>  <dbl>
 1 Mazda RX4          0.151 -0.105 -0.571  -0.535  0.568 -0.610   -0.777 -0.868  1.19   0.424  0.735
 2 Mazda RX4 Wag      0.151 -0.105 -0.571  -0.535  0.568 -0.350   -0.464 -0.868  1.19   0.424  0.735
 3 Datsun 710         0.450 -1.22  -0.990  -0.783  0.474 -0.917    0.426  1.12   1.19   0.424 -1.12 
 4 Hornet 4 Drive     0.217 -0.105  0.220  -0.535 -0.966 -0.00230  0.890  1.12  -0.814 -0.932 -1.12 
 5 Hornet Sportabout -0.231  1.01   1.04    0.413 -0.835  0.228   -0.464 -0.868 -0.814 -0.932 -0.503
 6 Valiant           -0.330 -0.105 -0.0462 -0.608 -1.56   0.248    1.33   1.12  -0.814 -0.932 -1.12 
 7 Duster 360        -0.961  1.01   1.04    1.43  -0.723  0.361   -1.12  -0.868 -0.814 -0.932  0.735
 8 Merc 240D          0.715 -1.22  -0.678  -1.24   0.175 -0.0278   1.20   1.12  -0.814  0.424 -0.503
 9 Merc 230           0.450 -1.22  -0.726  -0.754  0.605 -0.0687   2.83   1.12  -0.814  0.424 -0.503
10 Merc 280          -0.148 -0.105 -0.509  -0.345  0.605  0.228    0.253  1.12  -0.814  0.424  0.735
# … with 22 more rows
# ℹ Use `print(n = ...)` to see more rows

1
投票

我们可以使用:

library(dplyr)
library(tibble)

df <- mtcars %>% rownames_to_column()

df_new <- df %>% 
  mutate_if(is.integer, fun1)
© www.soinside.com 2019 - 2024. All rights reserved.