r - 使用更宽的枢轴 (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
我认为更宽的枢轴是要走的路,但它没有表现..
希望得到一些指导!
解决方案
我相信您需要一个“名称”列才能使用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 )
推荐阅读
- docker - 如何通信 mysql 和 mysqladmin docker 容器
- swift - 无法访问在全局常量文件中定义的枚举案例的原始值
- flutter - 在小部件之间传递数据
- react-native - 如何在本机反应中切换侧面菜单栏?
- angular - 密码验证未按预期工作
- c# - 如何使用 SQLiteCommand 对象获取自动递增的 ID 插入行
- numpy - 检查tictactoe游戏是否结束并返回获胜者
- javascript - 我不断收到 http POST http://localhost:3000/api/authenticate 404(未找到)
- python - 如何在不修改 sys.path 的情况下在 Python 中使用 libsvm?
- php - 如何在laravel中自动生成一个随机的、唯一的、字母数字字符串作为产品的序列号