【问题标题】:Reshape dataframe to be three columns wide without knowing variable names在不知道变量名称的情况下将数据框重塑为三列宽
【发布时间】:2019-03-31 22:19:17
【问题描述】:

我有一个列名未知但格式一致的数据框。如何在不使用列名的情况下将其重塑为三列宽?

cpu[,1:6]
  Datapoints.Timestamp Datapoints.Maximum Datapoints.Unit Datapoints.Timestamp.1 Datapoints.Maximum.1 Datapoints.Unit.1
1 2019-03-05T08:00:00Z           7.833333         Percent   2019-03-11T22:00:00Z                24.25           Percent

目标

Timestamp             Maximum   Unit
2019-03-05T08:00:00Z  7.833333  Percent
.....

数据集:

> dput(cpu[,1:6])
structure(list(Datapoints.Timestamp = structure(1L, .Label = "2019-03-05T08:00:00Z", class = "factor"), 
    Datapoints.Maximum = 7.83333333332848, Datapoints.Unit = structure(1L, .Label = "Percent", class = "factor"), 
    Datapoints.Timestamp.1 = structure(1L, .Label = "2019-03-11T22:00:00Z", class = "factor"), 
    Datapoints.Maximum.1 = 24.2500000000048, Datapoints.Unit.1 = structure(1L, .Label = "Percent", class = "factor")), .Names = c("Datapoints.Timestamp", 
"Datapoints.Maximum", "Datapoints.Unit", "Datapoints.Timestamp.1", 
"Datapoints.Maximum.1", "Datapoints.Unit.1"), class = "data.frame", row.names = c(NA, 
-1L))

【问题讨论】:

  • data.frame(matrix(data.frame(1,2,3,4,5,6), ncol = 3, byrow = TRUE))
  • @d.b 谢谢,我更新了问题,因为我的示例没有考虑日期。感谢您的帮助-我澄清了我的问题!

标签: r reshape


【解决方案1】:
do.call(rbind, lapply(seq(1, NCOL(df1), 3), function(i)
    setNames(df1[,i+(0:2)], colnames(df1)[1:3])))
#  Datapoints.Timestamp Datapoints.Maximum Datapoints.Unit
#1 2019-03-05T08:00:00Z           7.833333         Percent
#2 2019-03-11T22:00:00Z          24.250000         Percent

【讨论】:

    猜你喜欢
    • 2018-03-18
    • 1970-01-01
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-05
    • 1970-01-01
    相关资源
    最近更新 更多