【问题标题】:tidyverse gather multiple columnstidyverse 收集多个列
【发布时间】:2020-07-01 08:23:15
【问题描述】:

我有以下数据框:

df <- structure(list(ID = 1:4, col1.date = structure(c(1546188000,
1272294300, 1087908540, 1512241620), class = c("POSIXct", "POSIXt"
), tzone = "UTC"), col2.date = structure(c(1546237740, 1272928800,
1087966800, 1512277200), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
col3.date = structure(c(1546323000, 1272949200, 1088049600,
1512396000), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
col1.result = c(1.31, 0.95, 3.3, 0.55), col2.result = c(1.19,
1.57, 1.6, 0.59), col3.result = c(0.97, 2.13, 1.1, 0.57)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -4L))

我希望每个 ID 有三行两列:结果和日期。

这是我尝试过的:

df_long <- df %>%
gather(v, value, col1.date:col3.result) %>%
separate(v, c("var", "col")

但是我将日期转换为数字。

我做错了什么?

【问题讨论】:

  • 在您的gather 中,您正在组合numericPOSIXct 对象,因此它们都被强制转换为numeric。如果你想将它们结合起来,真的没有办法解决这个问题。当您稍后将它们与“正常”数字分开时,您的修复将是重新POSIX-ize 它们。 (顺便说一句,你的代码不完整,最后缺少一个右括号。你确定你给了我们实际的“工作”代码吗?)

标签: r pivot tidyverse reshape


【解决方案1】:

既然你最终想要重塑多个列(这是 tidyr-1.0.0 的“新方式”),那么试试pivot_longer。此答案直接改编自帮助页面中的示例?pivot_longer

df %>%
  pivot_longer(
    col1.date:col3.result,
    names_to = c("set", ".value"),
    names_pattern = "(.*)\\.(.*)"
  )
# # A tibble: 12 x 4
#       ID set   date                result
#    <int> <chr> <dttm>               <dbl>
#  1     1 col1  2018-12-30 16:40:00  1.31 
#  2     1 col2  2018-12-31 06:29:00  1.19 
#  3     1 col3  2019-01-01 06:10:00  0.97 
#  4     2 col1  2010-04-26 15:05:00  0.95 
#  5     2 col2  2010-05-03 23:20:00  1.57 
#  6     2 col3  2010-05-04 05:00:00  2.13 
#  7     3 col1  2004-06-22 12:49:00  3.3  
#  8     3 col2  2004-06-23 05:00:00  1.6  
#  9     3 col3  2004-06-24 04:00:00  1.1  
# 10     4 col1  2017-12-02 19:07:00  0.55 
# 11     4 col2  2017-12-03 05:00:00  0.59 
# 12     4 col3  2017-12-04 14:00:00  0.570

【讨论】:

  • OmryAtia,我明白了为什么需要重命名列;这不再需要。 (真是愚蠢……)
猜你喜欢
  • 1970-01-01
  • 2019-05-17
  • 2018-07-26
  • 1970-01-01
  • 2014-11-13
  • 2017-05-12
  • 2019-04-08
  • 2021-09-25
  • 1970-01-01
相关资源
最近更新 更多