基本的 R 方式不太优雅,但这是一种方法。
Result <- reshape(NYHSpot,direction = "wide",idvar="Year", timevar = "Month")
colnames(Result)[2:13] <- month.abb
Result
Year Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1 1986 0.420 0.340 0.460 0.420 0.410 0.411 0.434 NA NA NA NA NA
8 1987 0.557 0.556 0.523 0.518 0.541 0.516 0.454 0.489 0.474 0.509 0.504 0.542
20 1988 NA NA NA NA NA NA NA 0.449 0.461 0.452 NA NA
数据
NYHSpot <- structure(list(i..Spot.Price = c(0.42, 0.34, 0.46, 0.42, 0.41,
0.411, 0.434, 0.489, 0.474, 0.509, 0.504, 0.542, 0.557, 0.556,
0.523, 0.518, 0.541, 0.516, 0.454, 0.449, 0.461, 0.452), Month = c(6L,
7L, 8L, 9L, 10L, 11L, 12L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 11L, 12L, 1L, 2L, 3L), Year = c(1986, 1986, 1986, 1986,
1986, 1986, 1986, 1987, 1987, 1987, 1987, 1987, 1987, 1987, 1987,
1987, 1987, 1987, 1987, 1988, 1988, 1988)), class = "data.frame", row.names = c(NA,
-22L))
如果您没有安装 tidyr 软件包,请先安装它
install.packages("tidyr")
然后下面的代码就会做你想要的事情
library(tidyr)
# sample data
DF <- data.frame(Price = c(42,34,42,45,54,60),
Month = c(1,2,3,1,2,3),
Year = c(2000,2000,2000,2001,2001,2001))
DF %>%
mutate(Month = month.abb[Month]) %>%
pivot_wider(names_from = Month, values_from = Price)
结果:
Year Jan Feb Mar
<dbl> <dbl> <dbl> <dbl>
1 2000 42 34 42
2 2001 45 54 60