首页 > 解决方案 > 使用更宽的枢轴 (R) 将多条线变成一条线

问题描述

一如既往地为简单的 Q 道歉。我正在努力扩大支点来做我想做的事。

我有一个制表符分隔的数据集,如下所示:

ID  filepath
ID1 /tmp/ID1_1.txt
ID1 /tmp/ID1_2.txt
ID2 /tmp/ID2_1.txt
ID2 /tmp/ID2_2.txt
ID3 /tmp/ID3_1.txt
ID3 /tmp/ID3_2.txt

我想把它变成这样的东西:

ID  filepath_1  filepath_2
ID1 /tmp/ID1_1.txt  /tmp/ID1_2.txt
ID2 /tmp/ID2_1.txt  /tmp/ID2_2.txt
ID3 /tmp/ID3_1.txt  /tmp/ID3_2.txt

我认为更宽的枢轴是要走的路,但它没有表现..

希望得到一些指导!

标签: rdplyrtidyverse

解决方案


我相信您需要一个“名称”列才能使用pivot_wider(). 您可以使用mutate()例如创建一个

library(tidyverse)
df <- tibble::tribble(
         ~"ID", ~"filepath",
  "ID1", "/tmp/ID1_1.txt",
  "ID1", "/tmp/ID1_2.txt",
  "ID2", "/tmp/ID2_1.txt",
  "ID2", "/tmp/ID2_2.txt",
  "ID3", "/tmp/ID3_1.txt",
  "ID3", "/tmp/ID3_2.txt"
  )

df %>%
  mutate(names = ifelse(str_extract(filepath, "_.") == "_1", "filepath_1", "filepath_2")) %>% 
  pivot_wider(id_cols = ID, values_from = filepath, names_from = names)
#> # A tibble: 3 x 3
#>   ID    filepath_1     filepath_2    
#>   <chr> <chr>          <chr>         
#> 1 ID1   /tmp/ID1_1.txt /tmp/ID1_2.txt
#> 2 ID2   /tmp/ID2_1.txt /tmp/ID2_2.txt
#> 3 ID3   /tmp/ID3_1.txt /tmp/ID3_2.txt

reprex 包于 2021-07-23 创建 (v2.0.0 )


推荐阅读