简体   繁体   English

R重塑包装

[英]R reshape package

I am attempting to use R's "reshape" package to alter a data frame I have, pasted below. 我正在尝试使用R的“重塑”包来更改我粘贴在下面的数据框。 Basically, I would like to create a new data frame which concatenates variables V2 and V3 into columns for all possible combinations of V2 and V3, with rows as date. 基本上,我想创建一个新的数据框,将变量V2和V3连接到列中,以表示V2和V3的所有可能组合,并将行作为日期。 I have attempted using reshape's cast function, however I am unable to get the Date to appear in the rows. 我尝试使用reshape的cast函数,但是无法使Date显示在行中。 The variables are concatenated in column names as I want, but the Date is not included. 根据需要,变量在列名称中并置,但不包括日期。

This is the data frame std: 这是数据帧std:

V2      V3   V5       Date
AUS     CR   15344    2000-01-01
ALI     NG   3952     2000-01-01
EUR     CR   19296    2000-01-01
AUS     MO   5826     2000-01-01  

When I apply cast(std,Date~V2~V3,value="V5"), I obtain a frame as shown below, however I am unable to get the Date column to show as well. 当我应用cast(std,Date〜V2〜V3,value =“ V5”)时,获得如下图所示的框架,但是我也无法显示Date列。 I have done lots of trial and error with cast and melt to no avail. 我已经进行了大量的反复试验,但都没有成功。 Any suggestions would be appreciated 任何建议,将不胜感激

AUS.CR  ALI.NG  EUR.CR
15344   3952    19296
20108   4000    18568

You could use the package reshape (function cast ) or reshape2 with dcast : 您可以使用包reshape (功能cast )或reshape2dcast

x <- read.table(header=T,text='V2      V3   V5       Date
AUS     CR   15344    2000-01-01
ALI     NG   3952     2000-01-01
EUR     CR   19296    2000-01-01
AUS     MO   5826     2000-01-01')

With reshape and cast : 随着reshapecast

library(reshape)
cast(x, Date ~ V2 + V3, value='V5')
#         Date ALI_NG AUS_CR AUS_MO EUR_CR
# 1 2000-01-01   3952  15344   5826  19296

With reshape2 and dcast (same result) 使用reshape2dcast (结果相同)

library(reshape2)
dcast(x, Date ~ V2 + V3, value.var='V5')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM