簡體   English   中英

使用循環一次匯總一個以上變量和/或在R中應用

[英]aggregate on more than one variable at a time using loop and/or apply in R

我正在使用如下所示的數據幀( data )上的編程語言R:

   ID     t    P1    P2    P3    P4
    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1 100003     0     5     4     3     2
 2 100003     0     6     2     1     3
 3 100013     0     6     5     7     3
 4 100013     0     4     5     4     1
 5 100014     0     1     1     1     1
 6 100014     0     1     1     1     1
 7 100015     0     6     6     1     1
 8 100015     0     6     6     1     1
 9 100044     0     6     2     5     1
10 100044     0     6     3     1     1
11 100051     0    NA    NA    NA    NA
12 100051     0     4     4     2     2
13 100074     0     4     6     4     3
14 100074     0     5     6     3     2
15 100075     0     2     2     1     1

目的:我需要按ID匯總來自P1,P2,P3,P4的每個變量的ID(t始終等於0),如下所示:

new_data<-aggregate(P1~ID+t,data,mean,na.rm=T)
new_data<-aggregate(P2~ID+t,data,mean,na.rm=T)
new_data<-aggregate(P3~ID+t,data,mean,na.rm=T)
new_data<-aggregate(P4~ID+t,data,mean,na.rm=T)

問題:是否存在我可以運行的循環或apply系列的某些代碼,而不是手動檢查每個變量(P1-P4)。 非常感謝!

尚未測試過,但這應該可以完成循環:

cols<-c("P1","P2","P3","P4")
dat2<-lapply(data[cols],function(x){
  aggregate(x~ID+t, data, mean, na.rm=T)
})

您可以使用cbind(P1, P2, P3, P4) ~ ID + t一次聚合多個變量,或者等效地使用點代替cbind(P1, P2, P3, P4) 點表示每個剩余變量。

> aggregate(. ~ ID + t, old.data, mean,na.rm=T)
      ID t  P1  P2  P3  P4
1 100003 0 5.5 3.0 2.0 2.5
2 100013 0 5.0 5.0 5.5 2.0
3 100014 0 1.0 1.0 1.0 1.0
4 100015 0 6.0 6.0 1.0 1.0
5 100044 0 6.0 2.5 3.0 1.0
6 100051 0 4.0 4.0 2.0 2.0
7 100074 0 4.5 6.0 3.5 2.5
8 100075 0 2.0 2.0 1.0 1.0
>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM