[英]Wide to long format in R
Below is a snippet of my dataset: 以下是我的数据集的摘要:
> head(df)
Product Region Sector Type Date Value
Product A Capital Primary Continued 2012-01-01 395
Product C Capital Primary Continued 2012-01-01 37
Product D Capital Primary Continued 2012-01-01 208
Product A Central Primary Continued 2012-01-01 343
Product C Central Primary Continued 2012-01-01 1
Product D Central Primary Continued 2012-01-01 80
> tail(df)
Product Region Sector Type Date Value
Product C Southern Unknown New 2014-12-01 11
Product D Southern Unknown New 2014-12-01 18
Product A Zealand Unknown New 2014-12-01 19
Product B Zealand Unknown New 2014-12-01 10
Product C Zealand Unknown New 2014-12-01 9
Product D Zealand Unknown New 2014-12-01 6
I have 12 dates ranging from 2012-01-01 to 2014-12-01 and several factors of the variables. 我有12个日期,从2012-01-01到2014-12-01,以及变量的几个因素。 I would like to extrapolate on this dataset, ie. 我想对此数据集进行推断。 adding some extra random observations following 2014-12-01. 在2014-12-01之后添加了一些额外的随机观察结果。 My initial thought were to use dcast, eg: 我最初的想法是使用dcast,例如:
dcast(df, Date ~ Product + Region + Type + Sector)
In order to get the combination of all factors. 为了得到所有因素的结合。 This would result in a dataframe with 12 rows (the dates) and 118 columns (all the combinations of all factors). 这将导致数据帧具有12行(日期)和118列(所有因素的所有组合)。 I could then just add some rows to this dataframe and then convert it back using melt. 然后,我可以向该数据框添加一些行,然后使用melt将其转换回去。 But this doesn't seem to be a possibility. 但这似乎是不可能的。 Are there any other ways to do this? 还有其他方法吗?
You can just use rbind
- just make sure variable names are the same: 您可以只使用rbind
只需确保变量名称相同即可:
df <- data.frame(Product = c("Product A", "Product B", "Product C"), Region = c("Capital", "Capital", "Capital"),
Sector = c("Primary", "Primary", "Primary"), Type = c("Continued", "Continued", "Continued"),
Date = c("2012-01-01", "2013-01-01", "2014-12-01"), Value = c(397, 3, 456))
newdata <- data.frame(Product = c("Product A", "Product B", "Product C"), Region = c("Capital", "Capital", "Capital"),
Sector = c("Primary", "Primary", "Primary"), Type = c("Continued", "Continued", "Continued"),
Date = c("2014-12-01", "2014-12-02", "2014-12-03"), Value = c(1, 2, 3))
all(colnames(df) == colnames(newdata))
[1] TRUE
combined <- rbind(df, newdata)
combined
Product Region Sector Type Date Value
1 Product A Capital Primary Continued 2012-01-01 397
2 Product B Capital Primary Continued 2013-01-01 3
3 Product C Capital Primary Continued 2014-12-01 456
4 Product A Capital Primary Continued 2014-12-01 1
5 Product B Capital Primary Continued 2014-12-02 2
6 Product C Capital Primary Continued 2014-12-03 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.