【问题标题】:How to reshape/recast data in Excel from wide- to long-format如何将 Excel 中的数据从宽格式转换为长格式
【发布时间】:2017-08-23 20:38:29
【问题描述】:

我想将当前“宽”格式的 Excel 中的数据重新调整为“长”格式。您可以看到每个变量 (Column Name) 对应于任期、种族和成本负担。我想更轻松地将这些数据放入数据透视表中,但我不确定如何执行此操作。有什么想法吗?

仅供参考,数据是 HUD CHAS(住房和城市发展部,综合住房负担能力战略),其中有 20 多个表需要重新调整。

【问题讨论】:

  • 电源查询对此非常有用

标签: excel pivot-table reshape


【解决方案1】:

有一个简单的 R 脚本可以帮助解决这个问题。该函数接受您的 csv 文件的路径和您拥有的标头变量的数量。在我提供的示例图像/数据中,有 7 个标头变量。即实际数据(T9_est1)从第 8 列开始。

# Use the command below if you do not have the tidyverse package installed. 
# install.packages("tidyverse")
library(tidyverse)

read_data_long <- function(path_to_csv, header_vars) {
  data_table <- read_csv(path_to_csv)
  fields_to_melt <- names(data_table[,as.numeric(header_vars+1):ncol(data_table)])
  melted <- gather(data_table, fields_to_melt, key = 'variable', value = 'values')
  return(melted)
}

# Change the file path to where your data is and where you want it written to. 
# Also change "7" to the number of header variables your data has.
melted_data <- read_data_long("path_to_input_file.csv", 7)
write_csv(melted_data, "new_path_to_melted_file.csv")

(2018 年 7 月 25 日更新了更优雅的解决方案;2018 年 9 月 28 日再次进行了小改动。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-25
    • 2017-05-11
    • 1970-01-01
    • 2020-09-18
    • 2019-08-14
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多