给我举个例子帮我理解pivot_longer函数
时间: 2023-12-07 18:03:49 浏览: 31
好的,假设你有一份数据集,记录了四名学生在数学和语文两门课程上的成绩,数据如下:
| id | math_score1 | math_score2 | chinese_score1 | chinese_score2 |
|----|-------------|-------------|----------------|----------------|
| 1 | 80 | 90 | 75 | 85 |
| 2 | 85 | 95 | 80 | 90 |
| 3 | 90 | 100 | 85 | 95 |
| 4 | 95 | 105 | 90 | 100 |
现在你想将这份数据集从宽格式转换为长格式,即将科目和成绩两列合并成一列,并且添加一列记录原来是哪一门课程的成绩。你可以使用`pivot_longer`函数来实现。具体代码如下:
```R
library(tidyr)
scores <- data.frame(
id = 1:4,
math_score1 = c(80, 85, 90, 95),
math_score2 = c(90, 95, 100, 105),
chinese_score1 = c(75, 80, 85, 90),
chinese_score2 = c(85, 90, 95, 100)
)
scores_long <- pivot_longer(
scores,
cols = -id,
names_to = c("subject", ".value"),
names_pattern = "(.*)_(.*)"
)
scores_long
```
解释一下上面的代码:
- `cols = -id`表示除了`id`列以外的其他列都需要被转换;
- `names_to = c("subject", ".value")`表示将原来的列名分别转换成两列,一列是`subject`表示是哪一门科目的成绩,另一列是`.value`表示成绩的数值;
- `names_pattern = "(.*)_(.*)" `表示使用正则表达式将原来的列名拆分成两部分,第一部分是科目的名称,第二部分是数字编号。这样,就可以将原来的四列数据转换为两列数据。
运行上面的代码,你会得到一份新的数据集`scores_long`,如下所示:
| id | subject | value |
|----|---------|-------|
| 1 | math | 80 |
| 1 | math | 90 |
| 1 | chinese | 75 |
| 1 | chinese | 85 |
| 2 | math | 85 |
| 2 | math | 95 |
| 2 | chinese | 80 |
| 2 | chinese | 90 |
| 3 | math | 90 |
| 3 | math | 100 |
| 3 | chinese | 85 |
| 3 | chinese | 95 |
| 4 | math | 95 |
| 4 | math | 105 |
| 4 | chinese | 90 |
| 4 | chinese | 100 |
你可以看到,原来的四列成绩数据被转换为了两列数据,一列是`subject`表示科目名称,另一列是`value`表示成绩数值。同时,每一行记录都保留了原来的`id`列的关联性,方便后续的分析和处理。