我有一个数据框,该结构对于某些用途很好,但绝对不适合GGPLOT。有转换功能
x <- data.frame(head_1 = c(1,2,3,1,2,3),
head_2 = c(4,5,6,1,2,3),
date = c("01-01-2019","01-01-2019","01-01-2019","02-01-2019","02-01-2019","02-01-2019"))
进入
y <- data.frame(type= c("head_1","head_1","head_1","head_1","head_1","head_1",
"head_2","head_2","head_2","head_2","head_2","head_2"),
date = c("01-01-2019", "01-01-2019","01-01-2019","01-01-2019","01-01-2019","01-01-2019",
"02-01-2019", "02-01-2019","02-01-2019","02-01-2019","02-01-2019","02-01-2019"),
value= c(1,2,3,1,2,3,4,5,6,1,2,3 ))
答案 0 :(得分:2)
在tidyr软件包版本> 1.0中使用新的pivot_longer
函数可以在一行中执行转换。
library(tidyr)
y<-pivot_longer(x, cols = starts_with("head"), names_to = "type", values_to = "value")
y
A tibble: 12 x 3
date type value
<fct> <chr> <dbl>
1 01-01-2019 head_1 1
2 01-01-2019 head_2 4
3 01-01-2019 head_1 2
4 01-01-2019 head_2 5
5 01-01-2019 head_1 3
6 01-01-2019 head_2 6
7 02-01-2019 head_1 1
8 02-01-2019 head_2 1
9 02-01-2019 head_1 2
10 02-01-2019 head_2 2
11 02-01-2019 head_1 3
12 02-01-2019 head_2 3