gpt4 book ai didi

r - 对数据集中的多个配对列使用ivot_longer

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

我有一个看起来像这样的数据集:

input <- 
data.frame(
event = 1:2,
url_1 = c("g1", "g3"),
name_1 = c("dc", "nyc"),
url_2 = c("g2", "g4"),
name_2 = c("sf", "la"))

本质上,有一对以宽形式粘在一起的索引列。我想转换为long以给出以下输出:
output <- 
data.frame(
event = c(1,1,2,2),
url = c("g1", "g2", "g3", "g4"),
name = c("dc", "sf", "nyc", "la"))

我想使用 pivot_longer做到这一点。我已经试过了:
input %>% 
pivot_longer(contains("_"))

如何获得识别列对的功能?

最佳答案

您想在.value参数中使用names_to:

input %>%
pivot_longer(
-event,
names_to = c(".value", "item"),
names_sep = "_"
) %>%
select(-item)

# A tibble: 4 x 3
event url name
<int> <fct> <fct>
1 1 g1 dc
2 1 g2 sf
3 2 g3 nyc
4 2 g4 la

this article on pivoting:

Note the special name .value: this tells pivot_longer() that that part of the column name specifies the “value” being measured (which will become a variable in the output).

关于r - 对数据集中的多个配对列使用ivot_longer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61940984/

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