這裏有幾個可能性:
動物園包read.zoo
在zoo package可以產生多變量時間序列每系列的一列,即每ID一列。我們定義yr
從索引列中獲取年份,然後在我們讀入時使用split=
參數分割ID。我們使用aggregate=sum
來聚合剩餘的列 - 這裏只有一列。我們使用text = Lines來保持下面的代碼自身包含,但是有一個真實的文件,我們會用"myfile"
代替它。最後一行轉換結果。如果可以在列中而不是在行中有人,我們可以刪除該行。
Lines <- "1,28/02/2013,19.49
2,13/03/2013,16.68
3,15/03/2013,20.34
2,10/01/2014,28.43
3,12/06/2014,38.13
1,29/08/2014,68.46
1,20/12/2013,20.51
"
library(zoo)
# given a Date string, x, output the year
yr <- function(x) floor(as.numeric(as.yearmon(x, "%d/%m/%Y")))
# read in data, reshape & aggregate
z <- read.zoo(text = Lines, sep = ",", index = 2, FUN = yr,
aggregate = sum, split = 1)
# transpose (optional)
tz <- data.frame(ID = colnames(z), t(z), check.names = FALSE)
隨着發佈的數據,我們得到以下結果:
> tz
ID 2013 2014
1 1 40.00 68.46
2 2 16.68 28.43
3 3 20.34 38.13
見?read.zoo
,也是zoo-read
小插曲。
reshape2包下面是使用reshape2包的第二溶液:
library(reshape2)
# read in and fix up column names and Year
DF <- read.table(text = Lines, sep = ",") ##
colnames(DF) <- c("ID", "Year", "Value") ##
DF$Year <- sub(".*/", "", DF$Year) ##
dcast(DF, ID ~ Year, fun.aggregate = sum, value.var = "Value")
結果是:
ID 2013 2014
1 1 40.00 68.46
2 2 16.68 28.43
3 3 20.34 38.13
重塑功能這裏是不使用任何附加的溶液包。首先使用最後解決方案中標記爲##的三行讀取數據。這將產生DF
。然後聚集的數據,從長重塑它廣泛形式並最終固定起來的列名:
Ag <- aggregate(Value ~., DF, sum)
res <- reshape(Ag, direction = "wide", idvar = "ID", timevar = "Year")
colnames(res) <- sub("Value.", "", colnames(res))
其產生這樣的:
> res
ID 2013 2014
1 1 40.00 68.46
2 2 16.68 28.43
3 3 20.34 38.13
tapply功能。這個解決方案也不使用插件包。從最後的解決方案使用Ag
試試這個:
tapply(Ag$Value, Ag[1:2], sum)
更新:小的改進和3個額外的解決方案。
與1800萬行,你幾乎肯定希望看看'data.table'解決方案(用於讀取數據以及重塑) –