在 R 中高效地为大型数据帧创建转换矩阵
Efficiently creating a transition matrix for a large data frame in R
我在 R 中有一个 table,我需要在 R 中构建一个经验转换矩阵(计数)。
数据如下所示:
ExplicitRoll ExplicitRoll_EOM
No Change No Change
No Change 1-> 3
No Change No Change
NoChangeMonthOfPayoff NoChangeMonthOfPayoff
No Change Entry
NoChangeMonthOfPayoff NoChangeMonthOfPayoff
No Change No Change
....
这个 table 非常大并且有许多类型的其他列条目(例如 1->3
、charged off
等)。第一列代表月 t,第二列代表 t-1。
有没有一种方法可以非常有效地统计从一种状态到另一种状态的转换次数?作为参考,整个数据集是18M行。
谢谢!
table()
创建这样一个关联矩阵。您可以使用 as.data.frame.matrix
将其转换为数据帧。示例:
df = data.frame(Col1 = c("A","B","C","D","A","B","E"),Col2 = c("B","C","D","B","B","E","A"))
as.data.frame.matrix(table(df))
A B C D E
A 0 2 0 0 0
B 0 0 1 0 1
C 0 0 0 1 0
D 0 1 0 0 0
E 1 0 0 0 0
1800 万行:
df = data.frame(Col1 = sample(letters,18000000,replace = T),sample(letters,18000000,replace = T))
a = Sys.time()
as.data.frame.matrix(table(df))
Sys.time()-a
时差 0.5171118 秒。希望这对您有所帮助!
我在 R 中有一个 table,我需要在 R 中构建一个经验转换矩阵(计数)。
数据如下所示:
ExplicitRoll ExplicitRoll_EOM
No Change No Change
No Change 1-> 3
No Change No Change
NoChangeMonthOfPayoff NoChangeMonthOfPayoff
No Change Entry
NoChangeMonthOfPayoff NoChangeMonthOfPayoff
No Change No Change
....
这个 table 非常大并且有许多类型的其他列条目(例如 1->3
、charged off
等)。第一列代表月 t,第二列代表 t-1。
有没有一种方法可以非常有效地统计从一种状态到另一种状态的转换次数?作为参考,整个数据集是18M行。
谢谢!
table()
创建这样一个关联矩阵。您可以使用 as.data.frame.matrix
将其转换为数据帧。示例:
df = data.frame(Col1 = c("A","B","C","D","A","B","E"),Col2 = c("B","C","D","B","B","E","A"))
as.data.frame.matrix(table(df))
A B C D E
A 0 2 0 0 0
B 0 0 1 0 1
C 0 0 0 1 0
D 0 1 0 0 0
E 1 0 0 0 0
1800 万行:
df = data.frame(Col1 = sample(letters,18000000,replace = T),sample(letters,18000000,replace = T))
a = Sys.time()
as.data.frame.matrix(table(df))
Sys.time()-a
时差 0.5171118 秒。希望这对您有所帮助!