【问题标题】:gather() remove the row names of my dataframe. how can I have this row names?gather() 删除我的数据框的行名称。我怎么能有这个行名?
【发布时间】:2023-01-26 01:09:48
【问题描述】:

当我使用 tidyr gather() 函数并操作我的数据框时,我丢失了以前的行名。数据框。

这是我的 rstudio 控制台的输出

> DF <- as.data.frame((freethrows/Games), row.names = rownames(Games), col.names = colnames(Games))
> head(DF)
                   2005     2006     2007     2008     2009     2010     2011     2012     2013     2014
KobeBryant     8.700000 8.662338 7.597561 5.890244 6.013699 5.890244 6.568966 6.730769 3.000000 5.600000
JoeJohnson     3.182927 4.122807 3.853659 3.784810 2.894737 2.708333 2.633333 1.833333 2.012658 1.762500
LeBronJames    7.607595 6.269231 7.320000 7.333333 7.802632 6.367089 6.241935 5.302632 5.701299 5.434783
CarmeloAnthony 7.162500 7.061538 6.025974 5.621212 7.362319 6.584416 5.363636 6.343284 5.961039 4.725000
DwightHoward   4.341463 4.756098 6.451220 6.379747 5.890244 7.000000 5.203704 4.671053 4.915493 3.487805
ChrisBosh      6.771429 6.710145 7.044776 6.545455 6.714286 4.987013 4.017544 3.256757 2.822785 4.068182
> DF_gathered <- DF %>%
+   gather('2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', key = 'year', value = 'freeThrowsPerGame')
> head(DF_gathered)
  year freeThrowsPerGame
1 2005          8.700000
2 2005          3.182927
3 2005          7.607595
4 2005          7.162500
5 2005          4.341463
6 2005          6.771429
> 

在我将我的 DF 通过管道传输到 gather() 之后,我希望行名保留下来。

【问题讨论】:

  • 请提供足够的代码,以便其他人可以更好地理解或重现问题。
  • 使用 rownames_to_column() 将行名称转换为列
  • tidyverse 认为行名不是一个好主意,因此大多数函数将忽略或删除它们。 tidyverse 坚信所有数据都应该在适当的列中。如果您不同意,那么我只是想警告您,您会发现自己经常与这些功能作斗争。

标签: r dataframe tidyr rowname


【解决方案1】:

gather 已被取代。请改用pivot_longer。您还应该将行名作为列包含在内,否则 pivot_longer 将不会包含它们(如您所见)。如果你真的想要行名,你仍然可以在之后做tibble::column_to_rownames("player")

你可以做:

DF %>%
  tibble::rownames_to_column("player") %>%
  pivot_longer(-player, names_to = "year")

# A tibble: 60 × 3
   player     name  value
   <chr>      <chr> <dbl>
 1 KobeBryant 2005   8.7 
 2 KobeBryant 2006   8.66
 3 KobeBryant 2007   7.60
 4 KobeBryant 2008   5.89
 5 KobeBryant 2009   6.01
 6 KobeBryant 2010   5.89
 7 KobeBryant 2011   6.57
 8 KobeBryant 2012   6.73
 9 KobeBryant 2013   3   
10 KobeBryant 2014   5.6 
# … with 50 more rows

【讨论】:

    【解决方案2】:

    我们可以使用base R来做到这一点

    as.data.frame.table(as.matrix(DF))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-16
      • 2021-08-19
      • 2018-11-03
      • 2017-09-17
      • 1970-01-01
      • 2011-06-04
      相关资源
      最近更新 更多