Jun*_*tar 1 r list dataframe dplyr purrr
我试图重命名tibbles基于正则表达式的列表中的几列。
让我们看下面的例子:
library(tidyverse)
df1 <- tibble(
id_site = 1,
country = rep(paste0("country", 1:2), each = 3, len = 5),
species = rep(paste0("sp.", c(1, 3)), each = 3, len = 5),
min = c(100, 900, 2200, 400, 1300)
)
df2 <- tibble(
id_ref = 2,
country = "country3",
species = rep(paste0("sp.", 2:6), each = 1, len = 4),
min_alt = c(2700, 400, 600, 1800)
)
Run Code Online (Sandbox Code Playgroud)
我想重新命名id_site,以id_ref中df1和min_alt对min中df2。
我设法使用以下代码一次重命名一列:
list(df1, df2) %>%
set_names("df1", "df2") %>%
map(
~ .x %>%
rename_at(
colnames(.) %>% str_which("alt$"),
~ .x %>% str_replace(".+", "min")
) %>%
rename_at(
colnames(.) %>% str_which("site$"),
~ .x %>% str_replace(".+", "id_ref")
)
)
Run Code Online (Sandbox Code Playgroud)
但我觉得它很重复...
我想知道是否可以在单个rename_x函数中一次性完成此操作。
以下是不太重复的内容:
list(df1, df2) %>%
set_names("df1", "df2") %>%
map(~ .x %>%
rename_at(vars(matches("(alt|site)$")),
str_replace_all, pattern = c("_alt" = "", "site" = "ref")))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
75 次 |
| 最近记录: |