簡體   English   中英

將列條目的頻率匯總到R中的單獨列中

[英]Aggregating frequency of column entries into separate columns in R

我有一個數據框,看起來像:

POP<-c(rep("POP1",6), rep("POP2",6), rep("POP3", 6))
IID<-c(rep("POP1_1", 2), rep("POP1_2",2), rep("POP1_3", 2), rep("POP2_1",2), rep("POP2_2",2), rep("POP2_3",2), rep("POP3_1",2), rep("POP3_2",2),rep("POP3_3",2))
Site1<-c(36, 42, 32, 32, 48, 42, 36, 36, 48, 42, 36, 48, 28, 32, 32, 32, 48, 32)
Site2<-c(10, 8, 10, 16, 16, 10, 10, 10, 16, 10, -9, -9, 16, 8, 10, 10, 8, 8)
dat<-cbind(POP, IID, Site1, Site2)

有更多的網站列和更多的POP組。 我想按列瀏覽,對於該列中的每個不同條目,我都希望一個新列包含該條目的頻率,並在POP列中匯總。 -9表示缺失值。 我不希望這些內容構成專欄或對頻率有所貢獻。

最終,以上數據將如下所示:

dat

POP   Site1_28 Site1_32 Site1_36 Site1_42 Site1_48 Site2_8 Site2_10 Site2_16
POP1  0        0.333    0.167    0.333    0.166    0.167   0.5      0.333   
POP2  0        0        0.5      0.167    0.333    0       0.75     0.25    
POP3  0.167    0.667    0        0        0.167    0.5     0.333    0.167

我猜我會在使用table()和aggregate()的同時查看lapply(),但是我真的不知道從哪里開始。

謝謝!

我認為這應該做您想要的。 首先,我們進行一些數據操作以使對table的調用有效。 然后,我們遍歷兩列,通過每個POP值為站點執行一個prop.table 最后,我們使用rbindcbind合並數據。

#create data.frame
dat<-data.frame(POP, IID, Site1, Site2,
                stringsAsFactors = FALSE)
#identify columns containing 'Site'
site_col_names <- names(dat)[grep(pattern = 'Site', x = names(dat))]
#for each site column, recode -9 as NA, and then paste
for(i in site_col_names){
  dat[i] <- factor(sapply(dat[i], function(x) 
    ifelse(x == -9, NA, paste0(i,'_',x))))
}
#iterate over columns, calculate prop.table
do.call('cbind',
        lapply(site_col_names, function(n){
          do.call('rbind',
                  by(dat, dat$POP, function(d) prop.table(table(d[n]))))
        }))

      Site1_28  Site1_32  Site1_36  Site1_42  Site1_48  Site2_10  Site2_16   Site2_8
POP1 0.0000000 0.3333333 0.1666667 0.3333333 0.1666667 0.5000000 0.3333333 0.1666667
POP2 0.0000000 0.0000000 0.5000000 0.1666667 0.3333333 0.7500000 0.2500000 0.0000000
POP3 0.1666667 0.6666667 0.0000000 0.0000000 0.1666667 0.3333333 0.1666667 0.5000000

暫無
暫無

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

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