r语言 - 如何融化数据框



我有一个数据框,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()

我尝试过使用熔化功能,但我只是无法弄清楚如何使用它。

另外,你能发现我的图形代码有任何问题吗,这是行不通的吗?

我们可以使用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))

下次,请提供这样的可重现数据框。

df <- data.frame(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.5314460,
0.5135381, 0.4816461, 0.6414031),
D21 = c(0.3977892, 0.2142586, 0.4254800, 
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.6736790, 0.6612713,
0.7008503, 0.6351504, 0.6854996),
D252 = c(0.7517688, 0.727589, 0.7469207,      
0.7661933, 0.7307106, 0.7346074))

以下是您希望如何使用熔化功能。

library(reshape2)
dratiodf <- melt(df,
id.vars = "Date",
variable.name = "Type",
value.name = "Value")

然后,您的绘图应适用于以下内容。

ggplot(dratiodf, aes(x = Date, y = Value, group = Type)) +
geom_line() +
facet_wrap(~ Type) +
theme_wsj() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))

相关内容

  • 没有找到相关文章

最新更新