【发布时间】:2012-01-25 12:48:46
【问题描述】:
我是 R 的新手,所以如果我的问题的答案太明显,我深表歉意。我是一个如下形式的数据集:
Date, V1,V...,VN,Land,Nace
22/03/1995 23:01:12,1,3,2,15,A
21/03/1995 21:01:12,3,3,1,9,C
1/04/1995 17:01:06,3,2,1,3,B
我想按 Land、NACE(这是一个行业代码)、日期(我想将整个想法折叠为每周数据)和三个不同的回答选项来分析 data.frame 中的数据 {1, 2,3} 在 V1...VN 中。这是我的数据样本:
example <- as.data.frame(structure(c(" 1", " 2", " 1", " 2", " 1", " 1", " 2", " 1", " 2",
" 1", " 2", " 3", " 1", " 1", " 2", " 2", " 3", " 1", " 2", " 2",
" 1", " 2", " 1", " 1", " 2", NA, " 2", NA, NA, " 1", " 3", " 1",
" 3", " 3", " 2", " 3", " 3", " 3", " 2", " 2", " 2", " 3", " 3",
" 3", " 2", " 2", " 3", " 3", " 3", " 3", " 1", " 2", " 1", " 2",
" 2", " 1", " 2", " 1", " 2", " 2", " 2", " 3", " 1", " 1", " 2",
" 2", " 3", " 3", " 2", " 2", " 1", " 2", " 1", " 1", " 2", NA,
" 2", NA, NA, " 1", " 3", " 2", " 3", " 2", " 0", " 3", " 3",
" 3", " 2", " 0", " 2", " 3", " 3", " 3", " 0", " 2", " 2", " 3",
" 3", " 0", "12", " 5", " 9", "14", " 5", "tra", "tra", "man",
"inf", "agc", "07-2011", "07-2011", "07-2011", "07-2011", "07-2011"
), .indexCLASS = c("POSIXlt", "POSIXt"), .indexTZ = "", class = c("xts",
"zoo"), .indexFORMAT = "%U-%Y", index = structure(c(1297642226,
1297672737, 1297741204, 1297748893, 1297749513), tzone = "", tclass = c("POSIXlt",
"POSIXt")), .Dim = c(5L, 23L), .Dimnames = list(NULL, c("rev_sit",
"prof_sit", "emp_nr_sit", "inv_sit", "ord_home_sit", "ord_abr_sit",
"emp_cost_sit", "usage_cost_sit", "tax_cost_sit", "gov_cost_sit",
"rev_exp", "prof_exp", "emp_nr_exp", "inv_exp", "ord_home_exp",
"ord_abr_exp", "emp_cost_exp", "usage_cost_exp", "tax_cost_exp",
"gov_cost_exp", "land", "nace", "index"))))
prof_sit 等是问题,下面是 1、2、3 级的答案。 land、nace 和 index(即时间索引)是我想借助这些变量拆分数据集的变量。目标是获得一个 xts 数据框,如下所示:
-,nace.land,nace.land,nace.land,...
10-1995,sum of answers coded i.e. as 1 for a certain nace and a certain land,sum,sum,...
11-1995,sum,sum,...
12-1995,sum,sum,...
其中 12-1995 是 1995 年的第 12 个日历周。我最接近这个解决方案的是 tapply:
pos <- as.data.frame(tapply((example[,1]==3)*1,
list(example$index, example$land, example$nace), sum))
它或多或少地做了我想要的,因为 xts 对象的格式丢失了,因此行的顺序不正确。作为第二个缺点,还可能会提到我将运行循环以对所有 20 个问题应用相同的技术。有人知道这个问题的解决方案吗?我很感激每一个帮助或提示,因为我几天以来一直在这个问题上浪费时间。
最好的问候,
安德烈亚斯
【问题讨论】:
标签: r time-series xts