2017-05-10 17 views
0

我想從tm包中使用Zipf_plot函數來比較兩個不同的文檔術語矩陣 - 並且我不是R專家.. 也許你可以告訴我,如果有一種方法可以適用於這個功能?Zipf_plot():如何比較一個圖中的兩個對象?

Zipf_plot(x, type = "l", ...) 

我知道,有可能在一個窗口,從中獲取兩個(或更多):

par(mfrow=c()) 

,但我會很感激,在一個圖中,兩個或更多的DTM的解決方案。

在此先感謝! :-)

回答

1

你可以嘗試par(new=T)或嘗試根據自己的需要調整的功能,例如:

library(tm) 
data("acq") 
data("crude") 
m1 <- DocumentTermMatrix(acq) 
m2 <- DocumentTermMatrix(crude) 
Zipf_plot(m1, col = "red") 
par(new=T) 
Zipf_plot(m2, col="blue") 
Zipf_plot_multi <- function (xx, type = "l", cols = rainbow(length(xx)), ...) { 
    stopifnot(is.list(xx) & length(xx)==length(cols)) 
    for (idx in seq_along(xx)) { 
     x <- xx[[idx]] 
     if (inherits(x, "TermDocumentMatrix")) 
      x <- t(x) 
     y <- log(sort(slam::col_sums(x), decreasing = TRUE)) 
     x <- log(seq_along(y)) 
     m <- lm(y ~ x) 
     dots <- list(...) 
     if (is.null(dots$xlab)) 
      dots$xlab <- "log(rank)" 
     if (is.null(dots$ylab)) 
      dots$ylab <- "log(frequency)" 
     if (idx==1) { 
     do.call(plot, c(list(x, y, type = type, col = cols[idx]), dots)) 
     } else { 
     lines(x, y, col = cols[idx]) 
     } 
     abline(m, col = cols[idx], lty = "dotted") 
     print(coef(m)) 
    } 
} 
Zipf_plot_multi(list(m1, m2), xlim=c(0, 7), ylim=c(0,6)) 

enter image description here

+0

不錯!謝謝! 這個功能正是我一直在尋找的! :-) – Bay