gpt4 book ai didi

使用 purrr 重命名多个数据框列

转载 作者:行者123 更新时间:2023-12-03 22:36:36 26 4
gpt4 key购买 nike

我有以下数据框列表,其中包含名为 cyl 的列

# Create 3 dataframes with identical column names
mt_list <- list(head(mtcars[, 1:2]), tail(mtcars[, 1:2]), mtcars[13:18, 1:2])
mt_list
#> [[1]]
#> mpg cyl
#> Mazda RX4 21.0 6
#> Mazda RX4 Wag 21.0 6
#> Datsun 710 22.8 4
#> Hornet 4 Drive 21.4 6
#> Hornet Sportabout 18.7 8
#> Valiant 18.1 6
#>
#> [[2]]
#> mpg cyl
#> Porsche 914-2 26.0 4
#> Lotus Europa 30.4 4
#> Ford Pantera L 15.8 8
#> Ferrari Dino 19.7 6
#> Maserati Bora 15.0 8
#> Volvo 142E 21.4 4
#>
#> [[3]]
#> mpg cyl
#> Merc 450SL 17.3 8
#> Merc 450SLC 15.2 8
#> Cadillac Fleetwood 10.4 8
#> Lincoln Continental 10.4 8
#> Chrysler Imperial 14.7 8
#> Fiat 128 32.4 4

# New 'cyl' column names to change to (they are a character vector)
new_cyl_names <- c("cyl1", "cyl2", "cyl3")
new_cyl_names
#> [1] "cyl1" "cyl2" "cyl3"

我想命名 cyl成为字符向量中的对应值 new_cyl_names .

我尝试这样做:
# Custom function to change cyl to the 
# character value contained in new_colname
change_colname_cyl <- function(df, new_colname){
df %>%
dplyr::rename(new_colname = cyl)
}

# The following should change the names to cyl1, cyl2, cyl3
purrr::map2(.x = mt_list, .y = new_cyl_names, ~ change_colname_cyl(.x, .y))

这导致(仅显示第一个数据框):
[[1]]
mpg new_colname
Mazda RX4 21.0 6
Mazda RX4 Wag 21.0 6
Datsun 710 22.8 4
Hornet 4 Drive 21.4 6
Hornet Sportabout 18.7 8
Valiant 18.1 6

谁能帮我用 purrr正确地为此,即更改 cylcyl1在这种情况下,而不是 new_colname以上?

最佳答案

我对你的函数做了一点修改。我认为现在它有效。请参阅此 ( https://cran.r-project.org/web/packages/dplyr/vignettes/programming.html ) 以在 dplyr 中了解有关标准评估和非标准评估的更多信息.

library(tidyverse)

# List of data frames
mt_list <- list(head(mtcars[, 1:2]), tail(mtcars[, 1:2]), mtcars[13:18, 1:2])

# New column names
new_cyl_names <- c("cyl1", "cyl2", "cyl3")

# Create the function
change_colname_cyl <- function(df, new_colname){
df %>% rename(!!new_colname := cyl)
}

# Apply the function
map2(mt_list, new_cyl_names, ~ change_colname_cyl(.x, .y))
[[1]]
mpg cyl1
Mazda RX4 21.0 6
Mazda RX4 Wag 21.0 6
Datsun 710 22.8 4
Hornet 4 Drive 21.4 6
Hornet Sportabout 18.7 8
Valiant 18.1 6

[[2]]
mpg cyl2
Porsche 914-2 26.0 4
Lotus Europa 30.4 4
Ford Pantera L 15.8 8
Ferrari Dino 19.7 6
Maserati Bora 15.0 8
Volvo 142E 21.4 4

[[3]]
mpg cyl3
Merc 450SL 17.3 8
Merc 450SLC 15.2 8
Cadillac Fleetwood 10.4 8
Lincoln Continental 10.4 8
Chrysler Imperial 14.7 8
Fiat 128 32.4 4

更新

基于保罗的评论。以下似乎是重命名列的更直接和简洁的方法。
map2(mt_list, new_cyl_names, ~rename(.x, !!.y := cyl))

关于使用 purrr 重命名多个数据框列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46616591/

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