2012-01-10 60 views
3

工作,如果我有R中的數據集,它看起來像下面這樣:與分組數據中的R

ProjName,ProjLevel,Budget 
Proj1,Hardware,$100 
,Software,$100 
,Total,$200 
Proj2,Hardware,$200 
,Software,$300 
,Other,$400 
,Total,$900 
... 
... 

而且我要的數據是這樣的:

ProjName,ProjLevel,Budget 
Proj1,Hardware,$100 
Proj1,Software,$100 
Proj1,Total,$200 
Proj2,Hardware,$200 
Proj2,Software,$300 
Proj2,Other,$400 
Proj2,Total,$900 

我不知道如果這是最好的方法。理想情況下,我希望每個項目的「總計」預算金額。我想也許我可以在列上使用apply(),但不知道處理任務的最佳方式。

感謝, 拋

回答

3

不使用額外的軟件包,我會用一個循環,並與以前的非空單元格替換空單元格

my.table <-read.table(text="ProjName,ProjLevel,Budget 
Proj1,Hardware,$100 
,Software,$100 
,Total,$200 
Proj2,Hardware,$200 
,Software,$300 
,Other,$400 
,Total,$900", header=TRUE, as.is=TRUE,sep = ",") 

for (i in 1:nrow(my.table)){ 
if(my.table[i,1]=="") my.table[i,1] <-my.table[i-1,1] 
} 

給出:

> my.table 
    ProjName ProjLevel Budget 
1 Proj1 Hardware $100 
2 Proj1 Software $100 
3 Proj1  Total $200 
4 Proj2 Hardware $200 
5 Proj2 Software $300 
6 Proj2  Other $400 
7 Proj2  Total $900 

要獲得項目總金額:

my.table[my.table$ProjLevel=="Total",] 

    ProjName ProjLevel Budget 
3 Proj1  Total $200 
7 Proj2  Total $900 
+0

+1哎呀,誤讀了Totals位! – joran 2012-01-10 01:25:35

3

如果您在使用na.strings = ""讀取數據,然後你可以使用na.locf功能在動物園包填補缺失值與最新的非缺失之一:

my.table <-read.table(text="ProjName,ProjLevel,Budget 
+ Proj1,Hardware,$100 
+ ,Software,$100 
+ ,Total,$200 
+ Proj2,Hardware,$200 
+ ,Software,$300 
+ ,Other,$400 
+ ,Total,$900", header=TRUE, as.is=TRUE,sep = ",",na.strings = "") 

my.table$ProjName <- na.locf(my.table$ProjName) 
> my.table 
    ProjName ProjLevel Budget 
1 Proj1 Hardware $100 
2 Proj1 Software $100 
3 Proj1  Total $200 
4 Proj2 Hardware $200 
5 Proj2 Software $300 
6 Proj2  Other $400 
7 Proj2  Total $900 
+0

+1,但'na.locf'類屬於動物園,而不是xts。 – 2012-08-31 03:00:44