gpt4 book ai didi

r - 使用 `.value` 和 `pivot_longer()` 时如何将后缀附加到 `names_pattern`

转载 作者:行者123 更新时间:2023-12-04 13:27:00 26 4
gpt4 key购买 nike

我想用 pivot_longer()来自 {tidyr} 与 names_pattern将我的数据转换为长格式 保留列名中模式匹配之一的前缀字符串。
这似乎违反直觉,但我想在应用数据字典清理步骤之前转换为长格式,这需要原始列名。
设置

library(dplyr)
library(tidyr)

d <- tibble(id = 1,
other_var = "foo",
suffix_t1_value1 = "a",
suffix_t1_value2 = "b",
suffix_t2_value1 = "c",
suffix_t2_value2 = "d")
我所做的
> pivot_longer(d,
starts_with("suffix"),
names_pattern = "suffix_t(1|2)_(.*)",
names_to = c("rep", ".value"))

# A tibble: 2 x 5
id other_var rep value1 value2
<dbl> <chr> <chr> <chr> <chr>
1 1 foo 1 a b
2 1 foo 2 c d
期望输出
# A tibble: 2 x 5
id other_var rep suffix_t1_value1 suffix_t1_value2
<dbl> <chr> <chr> <chr> <chr>
1 1 foo 1 a b
2 1 foo 2 c d
我试过的
尝试 1
> pivot_longer(d,
starts_with("suffix"),
names_pattern = "suffix_t(1|2)_(.*)",
names_to = c("rep", "suffix_t1_{.value}"))
尝试 2
> pivot_longer(d,
starts_with("suffix"),
names_pattern = "suffix_t(1|2)_(.*)",
names_to = c("rep", paste0("suffix_t1_", ".value")))

最佳答案

我假设您想在 pivot_longer 中一步完成。 .我还没有弄清楚,如果可能的话,但如果两步过程没问题,那么下面的方法应该可行:

library(dplyr)
library(tidyr)

d %>% pivot_longer(starts_with("suffix"),
names_pattern = "suffix_t(1|2)_(.*)",
names_to = c("rep", ".value")
) %>%
rename_with(~ gsub("(.*)", "suffix_t1_\\1", .x),
starts_with("value"))

#> # A tibble: 2 x 5
#> id other_var rep suffix_t1_value1 suffix_t1_value2
#> <dbl> <chr> <chr> <chr> <chr>
#> 1 1 foo 1 a b
#> 2 1 foo 2 c d
创建于 2021-06-09 由 reprex package (v0.3.0)

更新
深入挖掘后 pivot_longer有点,我不认为可以访问 .valuepaste以及粘合语法 {.value}好像不支持。
但是,{tidyr} 提供了使用 build_longer_spec 进行旋转的构建块。这允许我们创建自己的 my_pivot_longer我们可以在其中包含 names_fn 的函数将一个函数应用于新列名的参数,在这里我们可以使用 gsub添加前缀或后缀。

my_pivot_longer <- function(data,
cols,
names_to = "name",
names_pattern = NULL,
names_fn = NULL) {

spec <- build_longer_spec(data,
cols,
names_pattern = names_pattern,
names_to = names_to)

if (!is.null(names_fn)) {
fn <- rlang::as_function(names_fn)
spec$.value <- fn(spec$.value)
}

pivot_longer_spec(data, spec)

}

d %>%
my_pivot_longer(starts_with("suffix"),
names_pattern = "suffix_t(1|2)_(.*)",
names_to = c("rep", ".value"),
names_fn = ~ gsub("(.*)", "suffix_t1_\\1", .x))
#> Note: Using an external vector in selections is ambiguous.
#> ℹ Use `all_of(cols)` instead of `cols` to silence this message.
#> ℹ See <https://tidyselect.r-lib.org/reference/faq-external-vector.html>.

#> This message is displayed once per session.
#> # A tibble: 2 x 5
#> id other_var rep suffix_t1_value1 suffix_t1_value2
#> <dbl> <chr> <chr> <chr> <chr>
#> 1 1 foo 1 a b
#> 2 1 foo 2 c d
创建于 2021-06-09 由 reprex package (v0.3.0)

关于r - 使用 `.value` 和 `pivot_longer()` 时如何将后缀附加到 `names_pattern`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67899327/

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