ava*_*ava 1 r unpivot reshape data-wrangling
我有一个 R 格式的数据框,如下表所示。我想将列“M1.1”、“M1.2”和“M1.3”合并为单个列“M1”,以便条目位于自己的行上(其他列中的 id 和值将重复)如第二个表所示。我可以使用什么函数来完成此任务?
| ID | M1.1 | M1.2 | M1.3 | M2 | M3 | M4 | M5 | M6 |
|---|---|---|---|---|---|---|---|---|
| 测试一个 | 测试t | 测试一个 | 测试y | 测试 | 测试t | 测试y | 测试你 | 测试w |
| 测试 | 测试r | 测试一个 | 测试时间 | 测试r | 测试j | 测试j | 测试w | 测试d |
| ID | M1 | M2 | M3 | M4 | M5 | M6 |
|---|---|---|---|---|---|---|
| 测试一个 | 测试t | 测试 | 测试t | 测试y | 测试你 | 测试w |
| 测试一个 | 测试一个 | 测试 | 测试t | 测试y | 测试你 | 测试w |
| 测试一个 | 测试y | 测试 | 测试t | 测试y | 测试你 | 测试w |
| 测试 | 测试r | 测试r | 测试j | 测试j | 测试w | 测试d |
| 测试 | 测试一个 | 测试r | 测试j | 测试j | 测试w | 测试d |
| 测试 | 测试时间 | 测试r | 测试j | 测试j | 测试w | 测试d |
我们可以使用pivot_longer:
library(dplyr)
library(tidyr)
df %>%
pivot_longer(
cols = c(M1.1, M1.2, M1.3),
names_to = "names",
values_to = "M1"
) %>%
select(id, M1, M2:M6)
Run Code Online (Sandbox Code Playgroud)
A tibble: 6 x 7
id M1 M2 M3 M4 M5 M6
<chr> <chr> <chr> <chr> <chr> <chr> <chr>
1 test a test t test test t test y test u test w
2 test a test a test test t test y test u test w
3 test a test y test test t test y test u test w
4 test s test r test r test j test j test w test d
5 test s test a test r test j test j test w test d
6 test s test h test r test j test j test w test d
Run Code Online (Sandbox Code Playgroud)
数据:
structure(list(id = c("test a", "test s"), M1.1 = c("test t",
"test r"), M1.2 = c("test a", "test a"), M1.3 = c("test y", "test h"
), M2 = c("test", "test r"), M3 = c("test t", "test j"), M4 = c("test y",
"test j"), M5 = c("test u", "test w"), M6 = c("test w", "test d"
)), row.names = c(NA, -2L), class = c("tbl_df", "tbl", "data.frame"
))
Run Code Online (Sandbox Code Playgroud)