2017-05-06 66 views
0

我正在寫一個函數來測量音頻文件列表中各個發音的持續時間。我需要將這些通話時間保存爲按文件組織的數字列表。當我編寫我的函數來打印任務時,它會按照我的意願打印列表,但不會將它們保存到外部變量中。但是,當我離開打印功能時,所有呼叫都將保存到一個列表中,而不指定來自哪個文件。有任何想法嗎?謝謝。將打印輸出保存爲R中的數字列表?

輸入:

callduration2 <- function(x) { 
    for (i in x) { 
     print(timer(i, threshold = 2, msmooth = c(400,90), dmin = 0.1, plot = FALSE)$s.end - timer(i, threshold = 2, msmooth = c(400,90), dmin = 0.1, plot = FALSE)$s.start) 
    } 
} 

輸出:

[1] 0.1035461 4.1581914 1.4687190 
[1] 0.2317160 0.3616587 0.3316719 0.2598854 0.2117248 0.2162683 0.1635642 1.0295460 
[1] 0.1035461 4.1581914 1.4687190 
[1] 0.2283603 0.1571119 0.1023054 
[1] 0.2795895 0.2531787 
[1] 0.7232425 1.0376167 0.5624210 0.1235691 0.3389063 

OR

輸入:

callduration <- function(x) { 
    output9 <- list() 
    for (i in x) { 
    i.t <- timer(i, threshold = 2, msmooth = c(400,90), dmin = 0.1, plot = FALSE) 
    output9 <- append(output9, i.t$s.end - i.t$s.start) 
    } 
    output9 
} 

輸出:

[[1]] 
[1] 0.1035461 

[[2]] 
[1] 4.158191 

[[3]] 
[1] 1.468719 

[[4]] 
[1] 0.231716 

[[5]] 
[1] 0.3616587 

[[6]] 
[1] 0.3316719 

[[7]] 
[1] 0.2598854 

[[8]] 
[1] 0.2117248 

[[9]] 
[1] 0.2162683 

[[10]] 
[1] 0.1635642 

[[11]] 
[1] 1.029546 

[[12]] 
[1] 0.1035461 

[[13]] 
[1] 4.158191 

[[14]] 
[1] 1.468719 

[[15]] 
[1] 0.2283603 

[[16]] 
[1] 0.1571119 

[[17]] 
[1] 0.1023054 

[[18]] 
[1] 0.2795895 

[[19]] 
[1] 0.2531787 

[[20]] 
[1] 0.7232425 

[[21]] 
[1] 1.037617 

[[22]] 
[1] 0.562421 

[[23]] 
[1] 0.1235691 

[[24]] 
[1] 0.3389063 
+3

你的輸入數據是什麼樣的? '計時器'從哪裏來,是矢量化的?你需要編輯[使你的例子可重現](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example#5963610)。更一般地說,'lapply'比'for'循環更有用,因爲您可以根據自己的喜好來設計結果。 – alistaire

+0

歡迎來到SO。我不明白你在這裏保存的意思。你能更詳細地描述你如何閱讀這些文件嗎? – DJJ

+0

要在@alistaire上展開一些好的建議,像'lapply(x,timer,threshold = 2,msmooth = c(400,90),dmin = 0.1,plot = FALSE)'會返回一個列表。這將調用定時器,爲x的每個元素傳遞附加參數(未測試) – epi99

回答

0

我在黑暗中拍攝。我的猜測會是這個。請記住,在函數中將返回最後一個對象。如果您願意,也可以使用命令return指定它。在你的第一個代碼中,你通過x循環,但不存儲結果並告訴函數輸出任何東西。

在您的第二個代碼中,您將結果存儲在一個列表中並將其返回,但我不確切知道您要查找的是哪種類型的輸出。

callduration2 <- function(x) { res <- matrix(nrow=length(x)) for (i in x) { res[i] <- timer(i, threshold = 2, msmooth = c(400,90), dmin = 0.1, plot = FALSE)$s.end - timer(i, threshold = 2, msmooth = c(400,90), dmin = 0.1, plot = FALSE)$s.start } return(res) }

myresults <- callduration2(x)

爲了避免寫循環,你可以做到以下幾點。

sapply(x,function(i) timer(i, threshold = 2, msmooth = c(400,90), dmin = 0.1, plot = FALSE)$s.end - timer(i, threshold = 2, msmooth = c(400,90), dmin = 0.1, plot = FALSE)$s.start)

0

也許你可以寫這樣的事情: 持續時間測量持續時間功能,什麼callduration回報是持續時間的載體,其名稱一樣的參數callduration。

duration <- function(x) { 
    t <- timer(x, threshold = 2, msmooth = c(400,90), dmin = 0.1, plot = FALSE) 
    t$s.end - t$s.start 
} 

callduration <- function(xs) { 
    durations <- sapply(xs, duration) 
    names(durations) <- names(xs) 
    durations 
} 
+0

這工作完美!非常感謝!! –