繁体   English   中英

tidyverse 收集多列

[英]tidyverse gather multiple columns

我有以下数据框:

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")

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

我究竟做错了什么?

由于您最终想要重塑多个列(这是 tidyr-1.0.0 的“新方式”),那么请尝试pivot_longer 此答案直接改编自?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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM