如何熔化数据框R

问题描述 投票:0回答:1

所以我有一个数据帧,dratiodf

   Date       D10       D21       D63      D126      D252
2019-09-23 0.1557585 0.3977892 0.8583822 0.7153107 0.7517688
2019-09-24 0.1513844 0.2142586 0.7501128 0.6736790 0.7275896
2019-09-25 0.5314460 0.4254800 0.8604258 0.6612713 0.7469207
2019-09-26 0.5135381 0.4250006 0.9424716 0.7008503 0.7661933
2019-09-27 0.4816461 0.2371428 0.7969672 0.6351504 0.7307106
2019-09-30 0.6414031 0.3407633 0.8207621 0.6854996 0.7346074

我想做的是将各列融合在一起,得到一个看起来像这样的数据框:

Date:        Type:  Value:
2019-09-23   D10    0.1557585
2019-09-23   D21    0.3977892
2019-09-23   D63    0.8583822
2019-09-23   D126   0.7153107
2019-09-23   D252   0.7517688
2019-09-34   D10    0.1513844
2019-09-34   D21    0.2142586

我想要这个,这样我就可以按类型来刻画最终的情节,像这样:

ggplot(dratiodf, aes(x=Date, y=Value))+
 geom_line()+
 facet_wrap(.~type)+
 theme_wsj()

我已经尝试过使用melt函数,但是我无法将其使用方法包起来。

您能帮忙吗?

此外,您能发现我的图形代码出现任何问题吗?这是行不通的?

谢谢您的时间,无论您的回答能力如何。

r ggplot2 melt facet-wrap
1个回答
1
投票

我们可以使用gather

library(tidyr) 
library(dplyr)
df1 %>%
  gather(Type, Value, -Date)

或使用pivot_longer(来自tidyr_1.0.0

df1 %>%
  pivot_longer(cols = - Date, names_to =  "Type", values_to = "Value")
# A tibble: 30 x 3
#   Date       Type  Value
#   <chr>      <chr> <dbl>
# 1 2019-09-23 D10   0.156
# 2 2019-09-23 D21   0.398
# 3 2019-09-23 D63   0.858
# 4 2019-09-23 D126  0.715
# 5 2019-09-23 D252  0.752
# 6 2019-09-24 D10   0.151
# 7 2019-09-24 D21   0.214
# 8 2019-09-24 D63   0.750
# 9 2019-09-24 D126  0.674
#10 2019-09-24 D252  0.728
# … with 20 more rows

数据

df1 <- structure(list(Date = c("2019-09-23", "2019-09-24", "2019-09-25", 
"2019-09-26", "2019-09-27", "2019-09-30"), D10 = c(0.1557585, 
0.1513844, 0.531446, 0.5135381, 0.4816461, 0.6414031), D21 = c(0.3977892, 
0.2142586, 0.42548, 0.4250006, 0.2371428, 0.3407633), D63 = c(0.8583822, 
0.7501128, 0.8604258, 0.9424716, 0.7969672, 0.8207621), D126 = c(0.7153107, 
0.673679, 0.6612713, 0.7008503, 0.6351504, 0.6854996), D252 = c(0.7517688, 
0.7275896, 0.7469207, 0.7661933, 0.7307106, 0.7346074)), 
 class = "data.frame", row.names = c(NA, 
-6L))
© www.soinside.com 2019 - 2024. All rights reserved.