我想在Excel中重塑我的数据,它目前是“宽”格式到“长”格式。您可以看到每个变量(Column Name
)对应于任期、种族和成本负担。我想更容易地将这些数据放到一个数据透视表中,但我不确定如何做到这一点。有什么想法吗?
仅供参考,数据是HUD CHAS (住房和城市发展部,全面住房负担能力战略),其中有20多个表格需要重塑。
发布于 2018-06-22 07:35:41
有一个简单的R脚本可以帮助你做到这一点。该函数接受csv文件的路径和您拥有的标头变量的数量。在我提供的示例image/data中,有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")
(用更优雅的解决方案更新了7/25/18;同样是9/28/18,做了一些小改动。)
https://stackoverflow.com/questions/45848895
复制相似问题