【问题标题】:Reshape data from long to wide format [duplicate]将数据从长格式重塑为宽格式[重复]
【发布时间】:2014-12-30 08:08:18
【问题描述】:

我的数据如下,

Date         Industry    Indices
2014/12/03   A           2.3
2014/12/03   B           3.4
2014/12/03   C           4.2
2014/12/03   D           3.0
2014/12/03   E           1.8
2014/12/04   A           2.7
2014/12/04   B           3.4
2014/12/04   C           4.5
2014/12/04   D           3.1
2014/12/04   E           2.1
2014/12/05   A           3.1
2014/12/05   B           2.5
2014/12/05   C           3.5
2014/12/05   D           3.1
2014/12/05   E           1.9

我想要的是这样的,

Date         A     B    C    D    E
2014/12/03   2.3   3.4  4.2  3.0  1.8
2014/12/04   2.7   3.4  4.5  3.1  2.1
2014/12/05   3.1   2.5  3.5  3.1  1.9

【问题讨论】:

  • 不知道你为什么称它为“提取”,但这是一个非常简单的操作,在 SO 中有很多骗子,例如library(reshape2) ; dcast(df, Date ~ Industry)
  • 您要查找的内容称为“枢轴”或“枢轴”。我敢肯定这里已经有几个关于这个的问题了。

标签: r transform extract


【解决方案1】:

你可以试试

library(tidyr)
spread(df, Industry, Indices)
#        Date   A   B   C   D   E
#1 2014/12/03 2.3 3.4 4.2 3.0 1.8
#2 2014/12/04 2.7 3.4 4.5 3.1 2.1
#3 2014/12/05 3.1 2.5 3.5 3.1 1.9

或使用base R

reshape(df, idvar='Date', timevar='Industry', direction='wide')

数据

df <- structure(list(Date = c("2014/12/03", "2014/12/03", "2014/12/03", 
"2014/12/03", "2014/12/03", "2014/12/04", "2014/12/04", "2014/12/04", 
"2014/12/04", "2014/12/04", "2014/12/05", "2014/12/05", "2014/12/05", 
"2014/12/05", "2014/12/05"), Industry = c("A", "B", "C", "D", 
"E", "A", "B", "C", "D", "E", "A", "B", "C", "D", "E"), Indices = c(2.3, 
3.4, 4.2, 3, 1.8, 2.7, 3.4, 4.5, 3.1, 2.1, 3.1, 2.5, 3.5, 3.1, 
1.9)), .Names = c("Date", "Industry", "Indices"), class = "data.frame",
row.names = c(NA, -15L))

【讨论】:

  • 什么是df?对不起。我是 R 的初学者。
  • @user3566160 df 是您的数据集对象。我复制了您的数据集并创建了对象df
  • @user3566160 您是否使用read.table/read.csv 等将数据集读入R
猜你喜欢
  • 1970-01-01
  • 2015-08-04
  • 2020-10-23
  • 2021-09-15
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多