pivot_wider 命令在 R 中生成一个 list() 而不是 "wider" data.frame

pivot_wider command generates a list() instead of a "wider" data.frame in R

我有 data.frame 两列,第一列显示年份的值,第二列显示纪元。

我使用 pivot_wider 命令创建两列:一列只有雨季值,一列有旱季值。但是,结果我得到了一个 list() 类型的对象,它有两个向量元素,一个是雨季的值,另一个是旱季的值。即使使用 as.data.frame() 命令,此对象也无法转换为具有干雨两列的 data.frame 格式。

dput

df<-structure(list(corr = c(0.74744744694889, 0.74744744694889, -0.74744744694889, 
0.710707994222, -0.672727272727273, -0.627272727272727, 0.721341509883808, 
0.74744744694889, 0.74744744694889, -0.74744744694889, 0.710707994222, 
-0.672727272727273, -0.627272727272727, 0.721341509883808, 0.74744744694889, 
0.74744744694889, -0.74744744694889, 0.706152173746218, -0.690909090909091, 
-0.627272727272727, 0.721341509883808, -0.569861483395246, -0.721861340047052, 
0.609081215121124, 0.74744744694889, 0.74744744694889, -0.74744744694889, 
0.664332608058143, 0.683373071367308, 0.608092810550575, -0.745454545454545, 
0.74744744694889, 0.74744744694889, -0.74744744694889, 0.664332608058143, 
0.683373071367308, 0.608092810550575, -0.745454545454545, -0.836363636363636, 
-0.74744744694889, 0.695967494156149, 0.608092810550575, 0.824603506116551, 
0.74744744694889, 0.74744744694889, -0.556029893992449, -0.682125853438958, 
0.556029893992449, 0.729285774909194), season = c("wet", "wet", 
"wet", "wet", "wet", "wet", "wet", "dry", "dry", "dry", "dry", 
"dry", "dry", "dry", "wet", "wet", "wet", "wet", "wet", "wet", 
"wet", "dry", "dry", "dry", "dry", "dry", "dry", "dry", "dry", 
"dry", "dry", "wet", "wet", "wet", "wet", "wet", "wet", "wet", 
"wet", "wet", "wet", "wet", "wet", "wet", "wet", "dry", "dry", 
"dry", "dry")), row.names = c(NA, -49L), class = "data.frame")

我试过这个:

  df2<-df%>%
    pivot_wider(names_from = season, values_from = corr)

输出

我想要一个只有两列的数据框: 干湿及其各自的值。

添加一个 id 列,事情变得更容易:

df %>%
  group_by(season) %>%
  mutate(id = row_number()) %>%
  pivot_wider(names_from = season, values_from = corr, id_cols = id)
# # A tibble: 28 × 3
#       id    wet    dry
#    <int>  <dbl>  <dbl>
#  1     1  0.747  0.747
#  2     2  0.747  0.747
#  3     3 -0.747 -0.747
#  4     4  0.711  0.711
#  5     5 -0.673 -0.673
#  6     6 -0.627 -0.627
#  7     7  0.721  0.721
#  8     8  0.747 -0.570
#  9     9  0.747 -0.722
# 10    10 -0.747  0.609
# # … with 18 more rows