将 pivot_longer 与宽数据集中的多个成对列一起使用 [英] Using pivot_longer with multiple paired columns in the wide dataset

查看:27
本文介绍了将 pivot_longer 与宽数据集中的多个成对列一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数据集:

I have a dataset that looks like this:

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 以提供此输出:

Essentially there are pairs of indexed columns that are stuck together in wide form. I want to convert to long to give this output:

output <- 
  data.frame(
    event = c(1,1,2,2),
    url = c("g1", "g2", "g3", "g4"),
    name = c("dc", "sf", "nyc", "la"))

我想使用 pivot_longer 来做到这一点.我试过这个:

I want to do this using pivot_longer. I've tried this:

input %>% 
  pivot_longer(contains("_"))

如何获得识别列对的函数?

How can I get the function to recognize the column-pairs?

推荐答案

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

You want to use .value in the names_to argument:

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   

来自这篇关于旋转的文章:

注意特殊名称 .value:它告诉 pivot_longer() 列名称的那部分指定了被测量的值"(它将成为输出中的变量).

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).

这篇关于将 pivot_longer 与宽数据集中的多个成对列一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆