如何将列中的值转换为行数?

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

我该如何转向 这个数据框:

enter image description here

进入如下表所示:

enter image description here

目标是列数等于月份列中的可用值,行数等于可用年份。我没有可重现的例子。

r dataframe csv transpose
2个回答
0
投票

基本的 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))

0
投票

如果您没有安装 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
© www.soinside.com 2019 - 2024. All rights reserved.