R 将数据从长格式改为宽格式
我的数据如下所示:R 将数据从长格式改为宽格式,r,transform,extract,R,Transform,Extract,我的数据如下所示: 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
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
你可以试试
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不确定为什么称之为“提取”,但这是一个非常简单的操作,在SO中有许多重复,例如library(reforme2);dcast(df,Date~Industry)
您正在寻找的是所谓的“枢轴”或“枢轴”。我相信在这里已经有几个问题了。什么是df?我很抱歉。我是R的初学者。@user3566160df
是您的数据集对象。我复制了您的数据集并创建了对象df
@user3566160您是否使用read.table/read.csv
等将数据集读入R
?
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))