我有一個數據幀A
與name
和type
。r創建一個類型使用頻率的彙總表
name aa tt gg cc aa at ag ac
type 3 2 4 3 2 2 3 3
如何創建一個新的排名data.frame B
與type
和時代 類型的號碼的計數發生在data.frame A
?
count 4 3 1
type 3 2 4
謝謝你的幫忙。
我有一個數據幀A
與name
和type
。r創建一個類型使用頻率的彙總表
name aa tt gg cc aa at ag ac
type 3 2 4 3 2 2 3 3
如何創建一個新的排名data.frame B
與type
和時代 類型的號碼的計數發生在data.frame A
?
count 4 3 1
type 3 2 4
謝謝你的幫忙。
一個選項是table()
函數。爲您的數據:
dat <- data.frame(name = c("aa","tt","gg","cc","aa","at","ag","ac"),
type = c(3,2,4,3,2,2,3,3))
它給:
> (tab <- with(dat, table(type)))
type
2 3 4
3 4 1
現在我們只需要對它進行排序:
> with(dat, sort(table(type), decreasing = TRUE))
type
3 2 4
4 3 1
:當然
> sort(tab, decreasing = TRUE)
type
3 2 4
4 3 1
這些步驟可以組合,
其他兩種可能更快的方法:
rev(sort(tapply(dat$type, dat$type, length)))
x <- do.call('data.frame', (rle(sort(dat$type)))); x[order(-x$lengths), ]
編輯: 都能跟得上上加文的數據集,他建議是最快的(使用win7的機器上測試,微基準)表的方法:
Unit: microseconds
expr min lq median uq max
1 RLE 614.452 650.376 669.971 713.3605 104852.7
2 TABLE 562.664 586.691 607.453 645.9440 128596.5
3 TAPPLY 585.525 626.115 643.144 689.0995 118123.8
+1不錯的選擇。但是我懷疑** data.table **對於大問題是最好的選擇。 –
謝謝,這是非常有幫助的。 –